0

I am working on a project for a friend who is looking for keith numbers (wolfram), and he is asking me to look through numbers in different bases. My problem is, I don't know how to convert numbers to higher bases because there aren't enough unique characters. I can only go to base 36 with letters, and base 62 with uppercase letters.

Does anyone know how I can express numbers in higher bases?

martineau
  • 119,623
  • 25
  • 170
  • 301
Adam Zaidi
  • 51
  • 3

2 Answers2

0

By "express higher numbers", do you mean show their digits, or actually calculating them?

If all you want to do is show their digits, you can always do it with a list, where each digit is an element of that list.

For example, if you wanted to show the number 10,000 in base 76, you could express/represent it this way:

 [1, 55, 44]  # the number ten-thousand in base seventy-six

So: 1 x 76^2 + 55 x 76^1 + 44 x 76^0 = 10,000

But if you need to calculate it? That's a different problem. Here's one way:

def get_digits(n, base=10):
    """Extracts the digits of n with base into an array.
       Only works on positive numbers."""
    if n == 0:
        return [0]
    digits = []
    while n > 0:
        n, r = divmod(n, base)
        digits[:0] = [r]
    return digits

You can call it like this:

get_digits(10_000, 76)  # returns [1, 55, 44]
J-L
  • 1,786
  • 10
  • 13
  • The way my program works is that it adds the digits, for example 2b_16, so 2_16+b_16 = d_16. I think this would work for getting the digits, but then for adding them I think I would need to calculate the actual number. – Adam Zaidi Aug 20 '20 at 18:07
  • @AdamZaidi, in that case, just convert 2_16 and d_16 to regular old Python `int`s, then add them together, then convert the result with the above `get_digits()` function. Python `int`s look like they're in base 10, but they're not really... they just print out in base 10 by default. – J-L Aug 20 '20 at 18:11
0

Note that obviously numbers are numbers, so the internal representation isn't a string of 0-9. It sounds like you just want to be able to show the digits for a number. The simplest algorithm I know of for that looks like this:

def digits(number: int, base: int):
    assert base > 0
    if number == 0:
        return [0]
    assert number >= 0
    ret = []
    to_process = number
    while to_process > 0:
        to_process, remainder = divmod(to_process, base)
        ret.append(remainder)
    # Convert to big-endian for familiarity
    return tuple(reversed(ret))

we can confirm it works as so:

>>> digits(10**10, 16)
(2, 5, 4, 0, 11, 14, 4, 0, 0)
>>> hex(10**10)
'0x2540be400'
Cireo
  • 4,197
  • 1
  • 19
  • 24