如何用另一种形式表示 (x ^ y) & 1?

3

我想要计算两个整数的汉明距离,我使用以下代码进行操作:

int count = 0;
for(int i = 0; i < 32; i++)
{
   if((x ^ y) & 1) 
       count++;
   x >>= 1;
   y >>= 1;
}

然而,它不能与以下内容一起使用:

if(x & 1 != y & 1)

当 x = 1, y = 4 时,正确的结果应该是 2。然而,第二个版本输出的是 1。听起来我需要学习离散逻辑。

如何改写第二个 if 语句以使其正常工作?


3
如果您启用所有警告,例如-Wparentheses,您将收到类似于“warning: suggest parentheses around comparison in operand of '&' ”的消息。这样可以节省时间。 - chux - Reinstate Monica
3个回答

9
< p > != 运算符比 & 运算符的 优先级 更高,因此按照原样书写的条件将被评估为 x & (1 != y) & 1,但你可能想要使用 (x & 1) != (y & 1)


它可以工作了,谢谢!我不知道它比 "&" 运算符的优先级更高。 - themennice

5

如果您想要汉明距离,为什么不直接使用std::popcount呢?

#include <bit>
...
int count = std::popcount(x ^ y);

如果您无法使用C++20,那么GCC和Clang也提供了编译器内置函数__builtin_popcount,而MSVC则提供了__popcnt

#ifdef _MSC_VER
#include <intrin.h>
#define __builtin_popcount __popcnt
#endif
...
int count = __builtin_popcount(x ^ y);

3
一些有用的popcount信息。 - chux - Reinstate Monica
谢谢。我还发现另一种解决方法:返回bitset<32>(x^y).count(); - themennice

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接