A unique way to reverse bits in C

Hello friends, today we came across a very unique method to reverse bits in C. We needed reversing bits of any byte or integer.

As an example

10011011 should be reversed to

11011001.

 

We came across this unique answer

reverse bits in c

This was done by Sth on stack overflow.

How this works?

First the higher nibble is swapped with lower nibble, then the higher two bytes of every nibble is swapped with lower of its own and lastly all the adjacent bits are swapped.

So this function works like this

b after first step         10111001

b after second step   11100110

b after third step        11011001

Amazon Auto Links: the template could not be found. Try reselecting the template in the unit option page.

by

Speak Your Mind

*