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 :-
Find the number of bits which are to be flipped to convert one integer to another.
For e.g, consider integers 11 ( 1011 ) & 5 ( 0101 ).
We see a mismatch in 3 bit positions. So, no. of bits to be flipped = 3.

Solution :-
Suppose the given integers are x & y. Logic is to get XOR of 'x' & 'y' [ z = x XOR y ] &
count the number of set bits in 'z'.
Please note that XOR of two bits would be '1' if they do not match.

#include<iostream>
using namespace std;

// count the no. of set bits in a positive integer
unsigned int countSetBits(unsigned int num) {
   unsigned int count = 0;
   while (num) {
      // bitwise AND operation to check if the
      // leftmost bit is set or not
      // if set, increment the count
      count += num & 1;
      // left shift the nm by one position
      num >>= 1;
   }
   return count;
}

// get the no. of bits to be flipped to convert 'a' to 'b'
unsigned int getNoBitsFlipped(int a, int b) {
   // xor of 'a' & 'b' will have set bits at those
   // places where bits of 'a' and 'b' differs
   unsigned int k = a ^ b;
   return countSetBits(k);
}

// main
int main() {
   int a = 41; // 101001
   int b = 28; // 011100
   int flip_bits = getNoBitsFlipped(a,b);
   cout<<"\nNo. of bits to be flipped :: "<<flip_bits;
   cout<<endl;
   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