How many characters should you allocate for a string representation of any given integer in any given base

doug
Tue, 26 Jan 2010 21:48:47 +0000

Once every while somebody asks how to calculate how many characters to allocate when building a string representation of an integer. This is actually a very easy problem.. when you know your maths.

The answer is simply to use logarithms!

floor(log10(number) + 1)

You tend to think of logarithms as the inverse function of exponentiation. For instance 10 to the power 2 renders a result of 100. The 10th logarithm of 100 results in 2. As we all know from our most basic maths lessons when you raise 10 to the nth power you get a string that is '1' followed with n repetitions of '0'. So we know that the length of 10 to the power n is always n + 1 characters long.

I won't bore you with a further maths lesson into how natural logarithms work but the bottom line is we can generalise all numbers to i * (base ^ n) where ^ is the exponentiation operator. This is also why we need to floor since log(22) + 1 will not return a whole integer.

We then employ the formula for calculating the logarithm of a number in any given base to this process and we result in the following generalised expression.

floor(log(number) / log(base) + 1)