繁体   English   中英

C中的MSB(最左位1位)索引

[英]MSB (1-bit most left) index in C

如何uint16_t符号整数( uint16_t )中获取最有意义的1位索引?

例:

uint16_t x = // 0000 0000 1111 0000 = 240
printf("ffs=%d", __builtin_ffs(allowed)); // ffs=4

有一个函数( __builtin_ffs__builtin_ffs符号整数返回最低有效1位(LSB)。

我想要相反的东西,我想要一些将8应用于上面的示例的函数。

备注 :我尝试构建自己的函数,但发现数据类型大小存在一些问题,具体取决于编译器。

从位于http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Other-Builtins.html的GCC手册中:

  • 内置函数:int __builtin_clz(无符号int x)

从最高有效位开始,返回x中前导0位的数目。 如果x为0,则结果不确定。

因此,最高设置位:

#define ONE_BASED_INDEX_OF_HIGHEST_SET_BIT(x) \
    (CHAR_BIT * sizeof 1 - __builtin_clz(x)) // 1-based index!!

注意x == 0x<0 && sizeof(x)<sizeof 0

如果我没看错(是吗?我对此东西有些生疏),可以按照以下步骤进行操作:

int msb = 0;
while(x) { // while there are still bits
    x >>= 1; // right-shift the argument
    msb++; // each time we right shift the argument, increment msb
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM