Bit order reversal function help
Author Message Bit order reversal function help

I've read through my books and the net and I just can't find much help
on writing a function that reverses the order of bits in an unsigned
int (to return a different number). Could someone explain to me where
i'm going wrong?  Also, this is for a class project, but I was also
wondering if someone could tell me how such a function would be
useful?

Thanks

unsigned reverse_bits(unsigned value)
{
static int size;
unsigned c, mask, out;
size=int_size();
out=0<< (size-1);

for (c=1;c<size; c++)
{
if (c!=size)
{
value>>=(size-c);
out=out|value;
}
}
return out;

Quote:
}

Thu, 26 Oct 2000 03:00:00 GMT  Bit order reversal function help

Someone sent me email helping me with the code.
Half way through it, I accidently hit the delete key.
Could you please re-send that email?

Thank you ever so much!

Thu, 26 Oct 2000 03:00:00 GMT  Bit order reversal function help

[---]

Quote:
> on writing a function that reverses the order of bits in an unsigned
> int (to return a different number). Could someone explain to me where

[---]
unsigned int reverse_bits( unsigned int value ) {
for(unsigned int check=1, out=0; check; check<<=1, value>>=1 )
out = out<<1 | value & 1;
return out;
Quote:
}

have fun
--ALfred

Fri, 27 Oct 2000 03:00:00 GMT  Bit order reversal function help

Quote:

>unsigned reverse_bits(unsigned value)
>{
>static int size;
>unsigned c, mask, out;
>size=int_size();
>out=0<< (size-1);

>for (c=1;c<size; c++)
>   {
>   if (c!=size)
>      {
>      value>>=(size-c);
>      out=out|value;
>      }
>   }
>return out;
>}

That's an extremely naive and inefficient way of doing it. Try this:

/*
* reverses the bottom 32 bits of the unsigned long
*/

unsigned long reverse(unsigned long input)
{
input = ((input & 0xAAAAAAAA) >> 1) | ((input & 0x55555555) << 1);
input = ((input & 0xCCCCCCCC) >> 2) | ((input & 0x33333333) << 2);
input = ((input & 0xF0F0F0F0) >> 4) | ((input & 0x0F0F0F0F) << 4);
input = ((input & 0xFF00FF00) >> 8) | ((input & 0x00FF00FF) << 8);
return  ((input & 0xFFFF0000) >> 16)| ((input & 0x0000FFFF) << 16);

Quote:
}

This works by grouping bits into pairs and then exchanging each
member of the pair, then exchanging adjacent pairs, then groups
of four, etc. By working on bits in parallel, it quite likely
works faster on most C compilers than the loop method.
To reverse only 16 bits, you reduce the number of rounds from
five to four, and you can truncate your bitmasks and use
unsigned int instead of unsigned long.

Fri, 27 Oct 2000 03:00:00 GMT

 Page 1 of 1 [ 4 post ]

Relevant Pages