这是一小段程序(14 行程序),它计算一个 number 中设置的位数。
输入-输出--> 0-->0(0000000), 5-->2(0000101), 7-->3(0000111)
int CountBits (unsigned int x)
{
static unsigned int mask[] = { 0x55555555,
0x33333333,
0x0F0F0F0F,
0x00FF00FF,
0x0000FFFF
} ;
int i ;
int shift ; /* Number of positions to shift to right*/
for (i =0, shift =1; i < 5; i ++, shift *= 2)
x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);
return x;
}
有人可以解释这里使用的算法/为什么会这样吗?