LearnFrenzy
Sign in Take a free test

Bitwise Operators · Bit Manipulation Programs · Question 4

Number of bits to flip to convert A into B in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Count how many bits must change to turn one number into another (the Hamming distance).

Solution
main.c
#include <stdio.h>

int bits_to_flip(unsigned a, unsigned b) {
    unsigned diff = a ^ b;          /* 1 wherever a and b differ */
    int count = 0;
    for (; diff; diff &= diff - 1)
        count++;
    return count;
}

int main(void) {
    printf("29 -> 15: %d bits\n", bits_to_flip(29, 15));
    printf("0 -> 255: %d bits\n", bits_to_flip(0, 255));
    return 0;
}

Output Verified by compiling and running

29 -> 15: 2 bits
0 -> 255: 8 bits

XOR marks every differing bit, and Kernighan's loop counts them. 29 = 11101 and 15 = 01111 differ in two places.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links