Macro to compute number of bits needed to store a number n
问题 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 ? 回答1: #define NBITS2(n) ((n&2)?1:0) #define NBITS4(n) ((n&(0xC))?(2+NBITS2(n>>2)):