常规实现,统计两个整数的异或结果中1的位数:
int hamming_distance(unsigned x, unsigned y)
{
int dist = 0;
// Count the number of bits set
for (unsigned val = x ^ y; val > 0; val >>= 1)
{
// If A bit is set, so increment the count
if (val & 1)
dist++;
// Clear (delete) val's lowest-order bit
}
// Return the number of differing bits
return dist;
}
另外,还可以借助编译器内置的popcount来更高效地实现:
int hamming_distance(unsigned x, unsigned y)
{
return __builtin_popcount(x ^ y);
}
//if your compiler supports 64-bit integers
int hamming_distance(unsigned long long x, unsigned long long y)
{
return __builtin_popcountll(x ^ y);
}