【发布时间】:2011-09-01 14:54:30
【问题描述】:
可能重复:
Best algorithm to count the number of set bits in a 32-bit integer?
仅使用 ! ~ & ^ | + > 运算符,我需要计算 32 位整数中设置的位数,而只能直接访问 8 位。所以只有 0xaa 而不是 0xaaaa
例如。 0x07 = 3 和 0x05 = 2
我也只能使用最多 40 个运算符。
现在我的解决方案使用 90 并且是:
int countBitsSet(int x)
{
int count = 0;
int mask = 0x01 // 00000001
count = (x & mask);
count += (x >> 1) & mask;
count += (x >> 2) & mask;
.
.
.
count += (x >> 31) & mask;
return count;
}
有谁知道将这个步骤减少一半的方法?我正在考虑找到一种方法来并行或其他方式并一次计算 4 位,但我不知道如何。其他人已经在 25 个运营商中做到了,所以我知道有办法。有什么想法吗?
【问题讨论】:
标签: c logic bit-manipulation