C代码宏拿到2的最小功率大于给定数目大 [英] C macro to get the smallest power of two greater than a given number
问题描述
我需要一个C宏来得到最小的电二期更大的超过一定数目。
I need a C macro to get the smallest of power two greater than a given number.
例如, FIRSTFREEBIT(0x16)
(二进制 1_0110
)必须等于为0x20
。
For example, FIRSTFREEBIT(0x16)
(binary 1_0110
) must be equal to 0x20
.
我要使用它作为:
#include <someheader.h> // defines SOME_X and SOME_Y
enum {
x = SOME_X,
y = SOME_Y,
z = FIRSTFREEBIT(x|y),
t = z << 1,
};
有一个相似,但略有不同的SO问题:
<一href=\"http://stackoverflow.com/questions/364985/algorithm-for-finding-the-smallest-power-of-two-thats-greater-or-equal-to-a-giv\">Algorithm寻找两个这是大于或等于给定值
A similar, but slightly different SO question: Algorithm for finding the smallest power of two that's greater or equal to a given value
推荐答案
看 __ builtin_clz
GCC内在。它会给你前导零比特,其可用于确定第一比特组的位置的数目。然后做 1
的左侧移位,时间的位置。
Look at the __builtin_clz
GCC intrinsic. It will give you the number of leading zero bits, which could be used to determine the position of the first bit set. Then do a left bit shift of 1
, times the position.
这篇关于C代码宏拿到2的最小功率大于给定数目大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!