Friday, 19 August 2016

Anirudh

Find the number of bits to be flipped to convert number A to number B

Problem statement: You are given two numbers A and B. Write a program to count the number of bits needed to be flipped to convert A to B.

Example: Let A = 5 and B = 3, then they can be represented in binary as:
     A = 1 0 1
     B = 0 1 1
As can be seen, total 2 bits are needed to be flipped to convert A to B in this case.

Solution: This problem can be restated as to find the number of dissimilar corresponding bits in A and B. And the bitwise XOR operator (^) can help us in finding that. The XOR of two bits is 1 only when the bits are not same. So, our solution involves two simple steps:

1. Find the bitwise XOR of A and B.
2. Count the number of set bits in the result.

int countFlippedBits(int a, int b)
{
    unsigned int count = 0;

    /* Bitwise XOR of a and b */
    unsigned int x = a ^ b;

    /* Finding the no. of set bits in the XOR result */
    while (x)
    {
        count += (x & 1);
        x >>= 1;
    }

    return count;
}

Anirudh

About the author →

Anirudh Khanna is a Computer Science student and a geek who firmly believes in the awesomeness of technology! He is a programmer and web designer, also keenly interested in the research of new and innovative ideas in Computer Science.

Subscribe to Geek Factorial via email :