C语言取二进制最高位1

膜拜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));
}
posted @ 2024-09-28 14:05  寻找繁星  阅读(50)  评论(0)    收藏  举报