C to get the smallest degree of power in excess of a given number

I need a C macro to get the smallest of the two powers exceeding a given number.

For example, FIRSTFREEBIT(0x16) (binary 1_0110 ) should be 0x20 .

I will 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: An algorithm for finding the least power of two greater than or equal to a given value

+1
c bit-manipulation c-preprocessor
May 30 '14 at 12:28
source share
2 answers

Here is my code, you can come up with 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
May 30 '14 at 12:29
source share

Take a look at the built-in GCC __builtin_clz . It will give you the number of initial zero bits that can be used to determine the position of the first set of bits. Then shift the left bit 1 , once per position.

+2
May 30 '14 at 12:36
source share



All Articles