Hi Rajeev,

I follow similar approach. The basic logic is swap bits of a pair, then swap
nibbles(2 bits) and then swap (4bits), 8bits  and go on.

So for ex. 0110 1101 1100 0101
In first step, I swap bits of each pair. So this becomes,

Input -  0110 1101 1100 0101
output- 1001 1110 1100 1010

In second step, I swap 2bits

Input - 1001 1110 1100 1010
output-0110 1011 0011 1010

I swap 4 bits now

Input - 0110 1011 0011 1010
output-1011 0110 1010 0011

Now I swap 8bits
Input - 1011 0110 1010 0011
output-1010 0011 1011 0110

So, now we have the bits in reverse order.

First step I do this way
x = ((x | 0xAAAA) >> 2) | (x<<2) | 0xAAAA;
Next step similarly
x = ((x | 0xCCCC) >> 4) | (x<<4) | 0xCCCC;

This is the logic.
Your code does the reverse way.

Regards,
Mithun

On Fri, Aug 5, 2011 at 6:04 PM, rShetty <[email protected]> wrote:

> This is the code to reverse the bits in an unsigned integer .
> Could anyone please explain the logic of this approach ? Thank You !!
>
> #define reverse(x) \
> (x=x>>16|(0x0000ffff&x)<<16, \
> x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8, \
> x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4, \
> x=(0xcccccccc&x)>>2|(0x33333333&x)<<2, \
> x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)
>
> --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>
>


-- 
Mithun.B.S
M:9916775380

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to