On Mar 21, 7:40 am, "hijkl" <[EMAIL PROTECTED]> wrote:
> . How to reverse all the bits in a unsigned integer? an signed
> integer (you have to keep the sign of the integer)?

For an unsigned int, the following algorithm can be used (I believe
you can find in in the "Hacker's Delight" book by H.Warren)  The idea
is to to swap bits with increasing distance each time:

uint bit_reverse (uint x)
{
  x = ((x & 0x55555555) << 1) | ((x & 0xaaaaaaaa) >> 1);
  x = ((x & 0x33333333) << 2) | ((x & 0xcccccccc) >> 2);
  x = ((x & 0x0f0f0f0f) << 4) | ((x & 0xf0f0f0f0) >> 4);
  x = ((x & 0x00ff00ff) << 8) | ((x & 0xff00ff00) >> 8);
  x = ((x & 0x0000ffff) << 16) | ((x & 0xffff0000) >> 16);
  return x;
}

The function doesn't have if's and should work pretty fast.  For 64-
bit numbers the solution is similar (masks are of double width and yet
another operation, shifting by 32 bits before return.

Regards,
Igor


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to