/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}
然后升级版本:
根据:表达式 x & =(x - 1) 可以删除x中最右边值为1的一个二进制位
解释:
Answer: If x is odd, then (x-1) has the same bit representation as x except that the rightmost 1-bit is now a 0. In this case, (x & (x-1)) == (x-1). If x is even, then the representation of (x-1) has the rightmost zeros of x becoming ones and the rightmost one becoming a zero. Anding the two clears the rightmost 1-bit in x and all the rightmost 1-bits from (x-1).所以升级后:
/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x &= (x-1))
b++;
return b;
}
加快了执行速度
本文介绍了一种高效的二进制位计数方法。通过使用x & (x-1)的操作来清除最右侧的1位,实现了更快的位计数。此方法尤其适用于需要频繁进行位计数的应用场景。
4264

被折叠的 条评论
为什么被折叠?



