C macro to get the smallest power of two greater than a given number

心已入冬 提交于 2019-12-24 11:01:13

问题


I need a C macro to get the smallest of power two greater than a given number.

For example, FIRSTFREEBIT(0x16) (binary 1_0110) must be equal to 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


回答1:


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))))))



回答2:


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.



来源:https://stackoverflow.com/questions/23954650/c-macro-to-get-the-smallest-power-of-two-greater-than-a-given-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!