The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Bit Manipulation

Problem :-
Reverse the bits of an unsigned integer.

Solution :-
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