Tuesday, November 19, 2013

Number of bits to change from one number to other

Given two numbers, calculate the number of bits required to change from one number to the other.

For example 12 in binary can be represented as 1100. 15 is represented as 1111. We need to change two bits to convert one number from the other as the last two bits are different.

We can find out the difference bits as follows. We first find out the XOR of two numbers. This gives us a bit pattern in which there is a set bit, if two bits differ. Then we can calculate the number of set bits in the XOR which gives the required answer.

Here is C++ code for this.