Question 4
Back to Exercise
Count how many bits must change to turn one number into another (the Hamming distance).
Solution
#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;
}
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!