我最近偶然发现了这段代码片段found on Wikipedia,想对正在发生的事情有所了解:

int hamming_distance(unsigned x, unsigned y)
{
int dist = 0;
unsigned  val = x ^ y;

// Count the number of bits set
while (val != 0)
{
    // A bit is set, so increment the count and clear the bit
    dist++;
    val &= val - 1;
}

// Return the number of differing bits
return dist;
}


在两个输入上执行异或运算有什么意义?

最佳答案

该函数基本上返回输入数字之间的不同位数。

这是通过对两个数字进行XOR运算而生成的,其中只有那些不同的位设置为1(请检查表here)。

从那时起,它只对XOR产生的输出中的位进行计数并返回它们。

09-10 00:17
查看更多