pythoncalgorithmradix

How to count the number of digits in numbers in different bases?


I'm working with numbers in different bases (base-10, base-8, base-16, etc). I'm trying to count the number of characters in each number.

Example

Number: ABCDEF

Number of digits: 6

I know about the method based on logarithms but I'm facing some problems.

  1. This Python script outputs that it failed to calculate the number of digits correctly in 3,969 numbers out of 1,000,000.

  2. I think the method that uses logarithms could be rather slow

Links:


Edit: certainly I can calculate the length of a string but what interests me most, is if it is possible to do the calculation without convention to string. I'd want to know the algorithm that could help to do it knowing just the source-base and the base to convert to.

Edit2: source-base is base-10 and the base to convert to can be any other base.


How can we calculate the number of digits in numbers in different bases?

If I know the number in base-10, how do I calculate the number of digits in the same number converted to base-16 (base-8, etc) without performing the conversion?

Note: some Python or C code will be greatly appreciated


Solution

  • Logarithms shouldn't really be slow. And you can easily calculate logarithms to any base by this formula: logBaseN(x)=logBaseA(x)/logBaseA(N) - you can use ln(Base e = 2.718...) or logBase10 or whatever you have. So you don't really need a program, a formular should do it:

    num_digets(N, base) = 1 + floor(log(N) / log(base))
    

    where N is your number and base the base you want that number in.

    For more explanation take a look here: http://www.mathpath.org/concepts/Num/numdigits.htm