计算无符号整数中的位数

标签 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 中返回其无符号整数参数的二进制表示的位数的最佳方法是什么?

最佳答案

这是一个不需要迭代的解决方案。它利用了这样一个事实,即在二进制中添加位完全独立于位的位置,并且总和永远不会超过 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;
}

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

关于计算无符号整数中的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780928/

相关文章:

c - 在 C 中的第 n 个 vs 起始位置 LinkedList 插入一个节点

c - 如何获取字符或数字的位值

c - 关于 C 中 test_bit 宏的问题

c++ - 右移开头为零

c++ - 将十进制转换为任何基数?

c - 在 C 中使用 calloc 初始化 int 数组,但没有接收到清零缓冲区

c - Linux 上使用的 malloc 版本

c++ - 通过网络构建和发送二进制数据

python - 将(大量)零写入二进制文件

math - 将整数限制为 0-255 并将双倍限制为 0.0-1.0 的技巧?