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 语句以使其工作?
如果你想要汉明距离,为什么不直接使用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)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |