gpt4 book ai didi

计算 unsigned long 中的位数

转载 作者:行者123 更新时间:2023-11-30 20:36:18 26 4
gpt4 key购买 nike

因此,我编写了这个函数来计算 long 中的位数,出于我的目的,该函数包括 MSB 右侧的零并排除其左侧的零:

int bitCount(unsigned long bits)
{
int len = 64;
unsigned long mask = 0x8000000000000000;
while ((bits & mask) == 0 && len > 0){
mask >>= 1;
--len;
}
return len;
}

就返回正确答案而言,这个函数对我来说工作得很好,但是有没有更好(更快或其他)的方法来做到这一点?

最佳答案

如果你想计算 long 中的位数类型,我建议您使用 ULONG_MAX来自 <limits.h> 头文件,并使用右移位运算符 >>计算一位的数量。这样您就不必事先实际知道位数。

类似于

unsigned long value = ULONG_MAX;
unsigned count = 1;

while (value >>= 1)
++count;

这是有效的,因为右移用零填充。

关于计算 unsigned long 中的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36479183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com