【问题标题】:Count the number of bits set using only bitwise operations [duplicate]计算仅使用按位运算设置的位数[重复]
【发布时间】: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


    【解决方案1】:

    1) 你计算出错误的结果;缺少 31 的班次。 2)您应该使用 for 循环。 3)搜索一下位计数算法会给你一堆链接。

    【讨论】:

    • 这只是一些 sudocode,我认为仅使用指定的运算符来构造循环是不可能的。
    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多