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);

>// mask=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.