# base 2 log of X

• 06-25-2007
Mario F.
base 2 log of X
I need to dinamically calculate the necessary bits to hold unsigned integrals subsets of varied size, sum these results and construct a std::bitset based on the final result.

But I can't seem to find a way to solve ceil(log2(x)) with the standard library.

The problem is with the log2(x), since apparently only the common and natural logarithms are offered.

Am I failing to see some other function? Is there a mathematical equivalent equation I can use?
• 06-25-2007
whiteflags
Quote:

Am I failing to see some other function? Is there a mathematical equivalent equation I can use?
logr(x) = logk(x) / logk(r)

Basically, using any constant radix, put log of x over the log of the desired radix and the answer is converted.
• 06-25-2007
This might help:
Code:

`loga(b) = log(b) / log (a)`
beaten by like a second![/edit]
• 06-25-2007
Mario F.
If it wasn't for that crude beard of yours I could kiss you.

Thanks a bunch!
• 06-25-2007
QuestionC
Don't use the log function to count bits. Putting aside the efficiency issue, consider accuracy. Since it turns the problem to floating point numbers, expressions like the following are ambiguous:

Code:

`int(log(4) / log(2)`
Is it int(.602059991/.301029995), or it int(.602059991/.301029996)? It's impossible to tell because of floating point precision.

Just shift bits if need be.
• 06-25-2007
QuestionC
Well, either shift bits or get creative if efficiency matters.
• 06-25-2007
Salem
> But I can't seem to find a way to solve ceil(log2(x)) with the standard library.
Isn't this going to be in effect the left most bit shifted left one place?

In binary, say you have 0101b (5) samples to store. The left-most bit is 0100b (4), which then shifted left one place is 1000b (8).
So you allocate space for 8, to store a maximum of 5 samples.

OK, maybe it's not the most accurate answer, but it's a lot easier to calculate.
• 06-26-2007
QuestionC
Actually, it's the number of bits.

ciel(log2(1-2)) -> 1
ciel(log2(3-4)) -> 2
ciel(log2(5-8)) -> 3

Well, there's the edge case on powers of 2, so technically floor(log2(x)) + 1. In any case, bit manipulation is totally the way to go.
• 06-26-2007
Mario F.
Thanks for the info guys. Much better options, no doubt.