计算无符号整数中的位数

时间:2013-02-08 20:37:11

标签: c binary bit-manipulation

我想在文件中编写一个名为bitCount()的函数:bitcount.c,它返回其无符号整数参数的二进制表示中的位数。

这是我到目前为止所做的:

#include <stdio.h>

int bitCount (unsigned int n);

int main () {
    printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n",
        0, bitCount (0));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
        1, bitCount (1));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 16\n",
        2863311530u, bitCount (2863311530u));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
        536870912, bitCount (536870912));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 32\n",
        4294967295u, bitCount (4294967295u));
    return 0;
}

int bitCount (unsigned int n) {
    /* your code here */
}

好的,当我刚刚运行时,我得到了:

# 1-bits in base 2 representation of 0 = 1, should be 0
# 1-bits in base 2 representation of 1 = 56, should be 1
# 1-bits in base 2 representation of 2863311530 = 57, should be 16
# 1-bits in base 2 representation of 536870912 = 67, should be 1
# 1-bits in base 2 representation of 4294967295 = 65, should be 32

RUN SUCCESSFUL (total time: 14ms)

它不会返回正确的位数。

在C中返回其无符号整数参数的二进制表示中的位数的最佳方法是什么?

3 个答案:

答案 0 :(得分:7)

这是一个不需要迭代的解决方案。它利用了以二进制方式添加位完全独立于位的位置并且总和不超过2位的事实。 00+00=0000+01=0101+00=0101+01=10。第一个添加同时添加16个不同的1位值,第二个添加8个2位值,后面每个值增加一半,直到只剩下一个值。

int bitCount(unsigned int n)
{
    n = ((0xaaaaaaaa & n) >> 1) + (0x55555555 & n);
    n = ((0xcccccccc & n) >> 2) + (0x33333333 & n);
    n = ((0xf0f0f0f0 & n) >> 4) + (0x0f0f0f0f & n);
    n = ((0xff00ff00 & n) >> 8) + (0x00ff00ff & n);
    n = ((0xffff0000 & n) >> 16) + (0x0000ffff & n);
    return n;
}

这是硬编码为32位整数,如果你的大小不同,则需要进行调整。

答案 1 :(得分:6)

 int bitCount(unsigned int n) {

    int counter = 0;
    while(n) {
        counter += n % 2;
        n >>= 1;
    }
    return counter;
 }

答案 2 :(得分:4)

事实证明,有一些非常复杂的方法可以按照here的答案进行计算。

下面的impl(我学会了回过头来)只是在每次迭代时循环敲掉最不重要的位。

int bitCount(unsigned int n) {

  int counter = 0;
  while(n) {
    counter ++;
    n &= (n - 1);
  }
  return counter;
}