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 ?
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.
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.
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.
#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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With