计算无符号整数中的位数

use*_*534 2 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 */
}
Run Code Online (Sandbox Code Playgroud)

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

# 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)
Run Code Online (Sandbox Code Playgroud)

它不会返回正确的位数.

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

Mar*_*som 7

这是一个不需要迭代的解决方案.它利用了以二进制方式添加位完全独立于位的位置并且总和不超过2位的事实.00+00=00,00+01=01,01+00=01,01+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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 好吧,现在我明白了,这是史诗般的 (2认同)

ogz*_*gzd 6

 int bitCount(unsigned int n) {

    int counter = 0;
    while(n) {
        counter += n % 2;
        n >>= 1;
    }
    return counter;
 }
Run Code Online (Sandbox Code Playgroud)

  • 根据"-1",我应该把理解部分留给你作为练习 (2认同)
  • 想想每条线的作用,它应该变得明显.这就是你学习的方式. (2认同)

小智 5

原来有一些相当复杂的方法来计算这是回答在这里.

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

int bitCount(unsigned int n) {

  int counter = 0;
  while(n) {
    counter ++;
    n &= (n - 1);
  }
  return counter;
}
Run Code Online (Sandbox Code Playgroud)