Likely the fastest way is by using a prepopulated lookup table.
const size_t bitsMap [] =
{
0, // value 0 (0)
1, // value 1 (1)
2, // value 2 (10)
2, // value 3 (11)
3, // value 4 (100)
// ...
};
You could also populate this array (or vector
or similar) by computing it at startup using mathematical means, such as ceil(log2(n))
.
You now have a number n
which you want to know how many bits will be needed to represent. You simply index the array using n
-- the value storesd there is the number of bits.
int main()
{
for (int i = 0; i < 256; ++i)
{
const size_t bits = bitsMap [i];
cout << "The number " << i << " would take " << bits << " to represent."
}
}
Indexing the array is immediate. I don't see how you'll get any faster than that.