Bit Manipulation

Reverse the bits of an unsigned integer.

We will use a combination of shift & OR operation to reverse the bits of an integer.
See the implementation below.

using namespace std;

// reverse the bits of the unsigned integer
void reverseBits(unsigned int &num) {
   int rev = 0;
   int i = sizeof(num)*8-1;
   while (i >= 0) {
      rev |= (num & 1);
      rev <<= 1;
      num >>= 1;
   num = rev;

int main() {
   unsigned int num = 13;
   cout<<"\nOriginal No. :: "<<num;
   cout<<"\nAfter reversing bits :: "<<num;
   return 0;

Back | Next

All problems on Bit Manipulation
* Count the number of set bits in an integer
* Find out whether a bit in a particular position in the binary representation of an unsigned integer is set or not
* Check if a number is a power of 2 using bit operation.
* Add two numbers without using any arithmetic operator
* Find the number of bits which are to be flipped to convert one integer to another
* Reverse the bits of an unsigned integer
About    Contact    Sitemap    Terms    Privacy