【问题标题】:What is the most efficient way of counting the number of 1's in an integer? [duplicate]计算整数中 1 的数量最有效的方法是什么? [复制]
【发布时间】:2012-02-11 21:17:17
【问题描述】:
【问题讨论】:
标签:
algorithm
optimization
numbers
compiler-optimization
【解决方案1】:
实际上有几个选项,我认为本地方式太慢了。
您可以使用查找表查找 8 位值,并从 unsigned int 值中并行查找所有四个字节,然后对结果求和。这个也可以很好地并行化(无论是多核,还是一些 SSE3/4 都可以提供帮助)。
您也可以采用 Brian Kernighan 的解决方案:
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
我前段时间在某处找到的最后一种可能的方法是(在 64 位机器上,因为那里的模运算会非常快):
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;