简体   繁体   English

这个C程序背后的逻辑是什么?

[英]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: 该算法本身会执行以下操作:

  1. Interpret adjacent bits as numbers (0 or 1) and add them. 将相邻的位解释为数字(0或1)并将其相加。 The results are numbers that can be represented with two bits (ie. 0 to 3). 结果是可以用两位表示的数字(即0到3)。
  2. Interpret adjacent pairs of bits as numbers (0 to 3) and add them. 将相邻的位解释为数字(0到3)并将它们相加。 The results can be represented with four bits (ie. 0 to 15). 结果可以用四个位(即0到15)表示。
  3. Interpret adjacent groups-of-4 bits as numbers (0 to 15) and add them. 将相邻的4解释为数字(0到15)并将它们相加。 The results can be represented with eight bits (ie. 0 to 255). 结果可以用八位(即0到255)表示。

...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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM