I saw the link http://pvtridvs.net/pool/bithacks.html#BitReverseObvious and posted the code here:
unsigned int v; // reverse the bits in this
unsigned int t = v; // t will have the reversed bits of v
int i;
for (i = sizeof(v) * 8 - 1; i; i--)
{
t <<= 1;
v >>= 1;
t |= v & 1;
}
Would someone explain a little bit why this look-simple algorithm works? I tested on paper some of the simplest examples, say 4-bit 0011 etc, it works, but I simply do not understand why these 3 lines of shift and bit-wise op can achieve it.
It shifts bits “out” of the low positions of
vand “in” to the low positions oft. Think of the variables as stacks of bits. You’re popping bits fromvand pushing them intot. Popping from one list and pushing onto another initially empty list is a simple way to reverse any list. The intialization just performs the initial “push” of the lowest order bit onto the result. This trick saves one pup and push (i.e. a right and left shift). E.g. for a byte, only 7 more pop-pushes are needed.