[英]What is the logic behind this C Program?
Here is a small piece of program (14 lines of program) which counts the number of bits set in a number . 这是一小段程序(14行程序),它计算number中设置的位数 。
Input-Output --> 0-->0(0000000), 5-->2(0000101), 7-->3(0000111) 输入输出-> 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;
}
Can someone explain the algorithm used here/why this works? 有人可以解释这里使用的算法/为什么有效吗?
This post , by Ian Ashdown, explains it in more detail: 这篇由伊恩·阿什当(Ian Ashdown)撰写的文章对此进行了更详细的解释:
Freed's numbers are members of a sequence, where the Nth number of the sequence is itself an infinite sequence from right to left of 2* N 1's followed by 2 *N 0's, followed 2**N 1's, and so on.
Freed的数字是序列的成员,其中序列的第N个数字本身是一个从右到左的无穷序列,从2 * N 1开始,然后是2 * N 0,然后是2 ** N 1,依此类推。 The initial numbers are:
初始数字为:
...0101010101010101
...0011001100110011
...0000111100001111
...0000000011111111
...
For a word size of 16 bits then, we have four "B-constants":
那么对于16位的字长,我们有四个“ B常数”:
B[1] = 0101010101010101
B[2] = 0011001100110011
B[3] = 0000111100001111
B[4] = 0000000011111111
So that's what those numbers in mask[]
are, eg. 这就是
mask[]
中的数字,例如。 0x55555555
is the hexadecimal representation of the bit pattern 1010101010101010101010101010101
. 0x55555555
是位模式1010101010101010101010101010101
的十六进制表示。
The algorithm itself does this: 该算法本身会执行以下操作:
...and so on, until you have a result that is as wide as however many bits you need. ...依此类推,直到得到的结果与所需的位数一样多。
I suggest that you try it on paper, by hand, with a few numbers using the binary masks above. 我建议您使用上面的二进制掩码手工在纸上尝试一些数字。 Then you might get a feel for the algorithm being expressed by that code.
然后,您可能会对该代码表示的算法有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.