//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));
}