Count Number of Bits to be Flipped to Convert A to B

Suppose, I have two numbers A and B. I need to find out how many numbers of bits needed to be changed to convert A to B.

Like:

A = 1101101
B = 1011011
^^ ^^
Here, we need to change 4 bits to convert A to B

How can I do this?

Solution:

1. Calculate XOR of A and B.
a_xor_b = A ^ B
2. Count the set bits in the above calculated XOR result.
countSetBits(a_xor_b)
XOR of two number will have set bits only at those places where A differs from B.

int countSetBits(unsigned int n) {
   unsigned int count = 0;
   while (n) {
      count += n & 1;
      n >>= 1;
   }
   return count;
}

// get the no. of bits to be flipped to convert 'a' to 'b'
int getNoBits(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);
}

One Thought on “Count Number of Bits to be Flipped to Convert A to B

  1. Anuj on July 10, 2016 at 1:23 am said:

    #include
    int bitcount(int);
    int main()
    {
    int a=2,b=4,c;
    c=a^b;
    int y=bitcount(c);
    printf(“%d Bits needed to be changed!”,y);
    return 0;
    }
    int bitcount(int x)
    {
    int b;
    for(b=0;x!=0;x>>=1)
    if(x&01)
    b++;
    return b;
    }

Leave a Reply to Anuj Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation