A small, comfortable nook pertaining to technology, current events, astronomy, and sailing and navigation.

Thursday, February 14, 2008

Bit Reversal By Bit-Banging

Here's an interesting C function to reverse the bits of an unsigned integer:
unsigned int reverse(unsigned int v)
{
v = (((v & 0xaaaaaaaa) >> 1) |
((v & 0x55555555) << 1));
v = (((v & 0xcccccccc) >> 2) |
((v & 0x33333333) << 2));
v = (((v & 0xf0f0f0f0) >> 4) |
((v & 0x0f0f0f0f) << 4));
v = (((v & 0xff00ff00) >> 8) |
((v & 0x00ff00ff) << 8));
return((v >> 16) | (v << 16));
}
I really need my reverse(0x77ff0300) in the morning! Sorry, bad joke (and for the odd word-wrapping)...

No comments: