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

the*_*ice 3 c++ bit-manipulation

我试图找到两个整数之间的汉明距离,我得到了它:

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

但是,它不适用于:

if(x & 1 != y & 1)
Run Code Online (Sandbox Code Playgroud)

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

如何重写第二个 if 语句以使其工作?

All*_*ind 9

!=经营者具有更高的优先级&运营商,这样写的情况作为评价x & (1 != y) & 1,但你可能要(x & 1) != (y & 1)代替。


Pat*_*rts 5

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

#include <bit>
...
int count = std::popcount(x ^ y);
Run Code Online (Sandbox Code Playgroud)

如果您不能使用 C++20,那么还有一个__builtin_popcount可用于 GCC 和 Clang 或__popcntMSVC 的内部编译器:

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

  • 一些有用的 [popcount](/sf/ask/3651311751/) 信息。 (3认同)