Macro to compute number of bits needed to store a number n

Viewed 4260

Let's say I need to write C macro that returns number of bits(1..32) needed to store unsigned 32-bit integer. (Result equals ceiling(log2(n)).

I need it as compile-time computed macro, not a function.

I could do

 #define NBITS(n) ((n)&(1<<31)?32:(n)&(1<<30)?31:...

it works, but is rather long. (Speed does not matter here, computation is at compile time).

Is there shorter way to write this macro ? Shortest ?

5 Answers
Related