代码之家  ›  专栏  ›  技术社区  ›  Artem Barger

计数数字中的位[重复]

  •  0
  • Artem Barger  · 技术社区  · 17 年前

    副本:

    Best algorithm to count the number of set bits in a 32-bit integer?


    3 回复  |  直到 6 年前
        2
  •  2
  •   billjamesdev    17 年前

    所以,这会给你一个 很快

    你可以稍微优化一下,但只需要一点迭代。只需创建一个8位版本的表解决方案,一个只有256个条目的表,然后迭代要检查的值中的每个BYTE,将表查找的结果相加。类似于:

    short int tableLookup[256] = { 0, 1, 1, 2, 1, ... };
    unsigned int valueToCheck = 89392491;
    int result = 0;
    while ( valueToCheck != 0 ) {
       result += tableLookup[ (valueToCheck & 0xFF) ];
       valueToCheck >>= 8;
    }
    // result should now have the correct bit count, if the table is correct.
    

    嗯,这似乎是众所周知的(在这里,我是在不假思索地做这件事的): http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

        3
  •  1
  •   arul    17 年前
    推荐文章