Reverse Bits of a given Integer

Given an integer, reverse its bits using binary operators.

 


 

The idea is to initialize the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, then we set the corresponding most significant bit in the result and finally move on to next bit in input number. We repeat this till all its bits are processed.

 
C++ implementation –
 

Download   Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

 


 

Optimized Solution –

Above solution will process all bits in an integer till its last set bit. It can be optimized to consider only set bits in an integer (which will be relatively less). The idea is to find position of the rightmost set bit in the number, and set the corresponding bit in result and finally unset the rightmost set bit. We repeat this till all set bits are processed.

Please refer below post to find position of the rightmost set bit and unset it
Bit Hacks – Part 3 (Playing with rightmost set bit of a number)
 

C++ implementation –
 

Download   Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂