可能重复:
Best algorithm to count the number of set bits in a 32-bit integer?
Counting the number of bits that are set
如果允许迭代循环的次数与设置的位数相同,则如何找到无符号整数中设置的位数(如果设置了3位,则只能迭代循环3次)< / p>
答案 0 :(得分:6)
这是我所知道的这样做的方法,它只会迭代v
中设置的位数,在执行结束时c
将保存v
中的位数1}}:
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
}
来源:C编程语言第二版。 (作者:Brian W. Kernighan和Dennis M. Ritchie)
示例:
v = 1010; //2 bits are set
v - 1 = 1010(10 decimal) - 1 = 1001(9 decimal)
1010
1001 &
------
1000 The least significant bit is unset, c is incremented by 1
v = 1000
v - 1 = 1000 - 1 = 0111
1000
0111 &
-------
0000 The least significant bit is unset again, c is incremented
by 1, the loop stops because there are no more set bits.