Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse bits the obvious way

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.

like image 636
user1559625 Avatar asked May 06 '26 08:05

user1559625


1 Answers

It shifts bits "out" of the low positions of v and "in" to the low positions of t. Think of the variables as stacks of bits. You're popping bits from v and pushing them into t. 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.

like image 103
Gene Avatar answered May 08 '26 23:05

Gene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!