#### 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; }