Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 220
Andrei Avatar asked Jul 26 '11 18:07

Andrei


People also ask

How many bits are required to store a digit?

Two bits can store 2*2 values, 4. Three bits can store 2*2*2 values, 8. And so on. So to store 3 values, you need at least two bits.

How many bits does it take to store 1 billion?

Alternatively, you should know that integers (with over 4 billion values) require 32-bits, therefore for 2 billion you'd need 31-bits and for 1 billion, 30-bits.

How do you set a bit in a macro?

Use the bitwise OR operator (|) to set a bit. number |= 1 << x; That will set bit x. Use the bitwise AND operator (&) to clear a bit.


1 Answers

#define NBITS2(n) ((n&2)?1:0)
#define NBITS4(n) ((n&(0xC))?(2+NBITS2(n>>2)):(NBITS2(n)))
#define NBITS8(n) ((n&0xF0)?(4+NBITS4(n>>4)):(NBITS4(n)))
#define NBITS16(n) ((n&0xFF00)?(8+NBITS8(n>>8)):(NBITS8(n)))
#define NBITS32(n) ((n&0xFFFF0000)?(16+NBITS16(n>>16)):(NBITS16(n)))
#define NBITS(n) (n==0?0:NBITS32(n)+1)
#include <iostream>
using namespace std;

int main(){
    cout << NBITS(0) << endl;
    cout << NBITS(1) << endl;
    cout << NBITS(2) << endl;
    cout << NBITS(3) << endl;
    cout << NBITS(4) << endl;
    cout << NBITS(1023) << endl;
    cout << NBITS(1024) << endl;
}

it is good?

like image 161
Adi Avatar answered Oct 08 '22 11:10

Adi