Willem <wi****@stack.nlwrites:
Martin wrote:
) Anyone know a good compile-time constant to tell you how many bits are
) needed to store a given value?
I'm not sure if the Standard requires it,
It is.
but on my compiler, a?b:c reduces
to a constant if the arguments are constants.
So you could use something like:
#define CALC_BITS_02(x) ((x) ? 1+CALC_BITS_03((x)>>1) : 0)
#define CALC_BITS_01(x) ((x) ? 1+CALC_BITS_02((x)>>1) : 0)
#define CALC_BITS_NEEDED ((x) ? 1+CALC_BITS_01((x)>>1) : 0)
Typo: you intended (x) after CALC_BITS_NEEDED.
One could also do something like:
#define CALC_BITS_NEEDED1(x) ((x) & 0x1u)
#define CALC_BITS_NEEDED2(x) ((x) & 0x2u ? 1+CALC_BITS_NEEDED1((x) >1) \
: CALC_BITS_NEEDED1((x) & 0x1u))
#define CALC_BITS_NEEDED4(x) ((x) & 0xcu ? 2+CALC_BITS_NEEDED2((x) >2) \
: CALC_BITS_NEEDED2((x) & 0x3u))
#define CALC_BITS_NEEDED8(x) ((x) & 0xf0u ? 4+CALC_BITS_NEEDED4((x) >4) \
: CALC_BITS_NEEDED4((x) & 0xfu))
#define CALC_BITS_NEEDED16(x) ((x) & 0xff00u ? 8+CALC_BITS_NEEDED8((x) >8) \
: CALC_BITS_NEEDED8((x) & 0xffu))
#define CALC_BITS_NEEDED32(x) ((x) & 0xffff0000lu ? \
16+CALC_BITS_NEEDED16((x) >16) : \
CALC_BITS_NEEDED16((x) & 0xffffu))
or shorten that by:
#define CALC_BITS_NEED4(x) ((x) 1 ? 2 : (x) & 1)
--
Ben.