C语言取二进制最高位1

阅读量: searchstar 2020-03-22 17:48:34
Categories: Tags:

膜拜mstlq:https://bbs.csdn.net/topics/330068401

//find the Power of 2 that Greater than or Equal to x
uint32_t p2ge(uint32_t x) {
--x;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x + 1;
}

改一下就是我们要的
//x = 0时结果未定义
uint32_t highbit(uint32_t x) {
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return (x >> 1) + 1;
}

也可以用__builtin_clz
//x = 0时结果未定义
uint32_t highbit(uint32_t x) {
return 1u << (31 - __builtin_clz(x));
}