Compile time computing of number of bits needed to encode n different states
Try this:
constexpr unsigned numberOfBits(unsigned x)
{
return x < 2 ? x : 1+numberOfBits(x >> 1);
}
Simpler expression, correct result.
EDIT: "correct result" as in "the proposed algorithm doesn't even come close"; of course, I'm computing the "number of bits to represent value x"; subtract 1 from the argument if you want to know how many bits to count from 0 to x-1. To represent 1024 you need 11 bits, to count from 0 to 1023 (1024 states) you need 10.
EDIT 2: renamed the function to avoid confusion.
The minimum number of bits required to store n
different states is ceil(log2(n))
.
constexpr unsigned floorlog2(unsigned x)
{
return x == 1 ? 0 : 1+floorlog2(x >> 1);
}
constexpr unsigned ceillog2(unsigned x)
{
return x == 1 ? 0 : floorlog2(x - 1) + 1;
}
Note that ceillog2(1) == 0
. This perfectly fine, because if you want to serialize an object, and you know that one of its data members can only take on the value 42
, you don't need to store anything for this member. Just assign 42
on deserialization.