[英]C macro to get the smallest power of two greater than a given number
I need a C macro to get the smallest of power two greater than a given number. 我需要一个C宏来获得比给定数字大2的最小幂。
For example, FIRSTFREEBIT(0x16)
(binary 1_0110
) must be equal to 0x20
. 例如, FIRSTFREEBIT(0x16)
(二进制1_0110
)必须等于0x20
。
I am going to use it as: 我将其用作:
#include <someheader.h> // defines SOME_X and SOME_Y
enum {
x = SOME_X,
y = SOME_Y,
z = FIRSTFREEBIT(x|y),
t = z << 1,
};
A similar, but slightly different SO question: Algorithm for finding the smallest power of two that's greater or equal to a given value 一个类似但略有不同的SO问题: 用于查找两个大于或等于给定值的最小幂的算法
Here's my code, you are welcome to invent something better: 这是我的代码,欢迎您发明更好的东西:
#define __OR_RSHIFT__(n,x) ((x)|(x)>>n)
#define FIRST_UNUSED_BIT(x) (1+__OR_RSHIFT__(16,__OR_RSHIFT__(8,__OR_RSHIFT__(4,__OR_RSHIFT__(2,__OR_RSHIFT__(1,x))))))
Look at the __builtin_clz
GCC intrinsic. 查看__builtin_clz
GCC内部函数。 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. 然后将位置左移1
倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.