Hamming distance
Count how many bit positions differ between two numbers by XORing them and counting the set bits.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
XOR gives a 1 wherever two bits disagree and a 0 wherever they agree, so x ^ y has exactly one set bit for every position x and y differ in. Counting those set bits, with the same n & (n - 1) trick as Count set bits, gives the Hamming distance directly.
Code
public static int HammingDistance(int x, int y) {
int xorValue = x ^ y; // a 1 marks every bit where x and y differ
int distance = 0;
while (xorValue != 0) {
xorValue &= xorValue - 1; // clear the lowest set bit
distance++;
}
return distance;
}static int hammingDistance(int x, int y) {
int xorValue = x ^ y; // a 1 marks every bit where x and y differ
int distance = 0;
while (xorValue != 0) {
xorValue &= xorValue - 1; // clear the lowest set bit
distance++;
}
return distance;
}int hammingDistance(int x, int y) {
int xorValue = x ^ y; // a 1 marks every bit where x and y differ
int distance = 0;
while (xorValue != 0) {
xorValue &= xorValue - 1; // clear the lowest set bit
distance++;
}
return distance;
}def hamming_distance(x: int, y: int) -> int:
xor_value = x ^ y # a 1 marks every bit where x and y differ
distance = 0
while xor_value != 0:
xor_value &= xor_value - 1 # clear the lowest set bit
distance += 1
return distanceTips
- The Hamming distance is 0 exactly when x equals y, since then x ^ y is 0.
- This generalizes to any fixed-width data, not just integers, wherever "how different are these two bit patterns" matters.
In the .NET library
Counting set bits in x ^ y is exactly the Count set bits lesson applied to one extra value; the two lessons share the same clearing loop.