Today, we have a simple bit manipulation problem wherein we’re given a 32-bit unsigned integer and asked to reverse the bits and return them.

Input:  [10000010100101000001111010011101]
Output: [10111001011110000010100101000001]

I won’t go into too much detail for this one, but my general approach is to build the return value bit by bit, left to right while reading bits from the input integer right to left.

uint32_t reverseBits(uint32_t n) {
   uint32_t result = 0;
   for(int i=0;i<32;i++) {
	  // left shift result
	  result <<= 1;
	  result += n & 1;
	  // right shift input
	  n >>= 1;
   }
   return result;
}

For those rusty on the bitwise operators, I translated the critical section to integer operators just for a comparison to see how we’re operating on the integer value:

uint32_t reverseBits(uint32_t n) {
   uint32_t result = 0;
   for(int i=0;i<32;i++) {
	  result *= 2;
	  result += (n%2 == 1);
	  n /= 2;
   }
   return result;
}

That’s it for today. Check back tomorrow for another problem discussion!