gpt4 book ai didi

c - 如何获得数字的第一个设置位的位置

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:33 24 4
gpt4 key购买 nike

例如,我的定义如下所示:

#define AA              0x0000000000000001LL
#define BB 0x0000000000000002LL
#define CC 0x0000000000000004LL
#define DD 0x0000000000000008LL
#define EE 0x0000000000000010LL
#define FF 0x0000000000000020LL
#define GG 0x0000000000000040LL
#define HH 0x0000000000000080LL

我想从最大定义中获取第一个设置位(从最低有效位向后计数)的位置。

h = getAmountFromBitwise(HH);
output of h is 8;
b = getAmountFromBitwise(BB);
output b is 2;

有没有更好的方法来实现 getAmountFromBitwise()?

int getAmountFromBitwise(long long input) {
2^x = input;
y=x+1;
return y;
}

最佳答案

我会将其用作您的 getAmountFromBitwise()

int highest_bit_set(long long n) {
int result = 1;
while(n >>= 1) /* keep shifting right until n == 0 */
result++;
return result;
}

请注意,这需要 n != 0 才能获得正确的结果。

关于c - 如何获得数字的第一个设置位的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062656/

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