Search code examples
pythonnumber-systems

Is it possible to change number systems in python?


This may sound similar to many other questions, but I couldn't find an answer to mine. I'm wondering if you can switch the number system of any number. For example,

x = 10
y = int(10, 3)

How can I switch x into a base-3 number system? This is the solution I've seen but it hasn't worked. I know that for binary, decimal, and hexadecimal systems there is a separate function but I don't know of anything for other number systems.


Solution

  • from https://stackoverflow.com/a/39884219/11070463, here's a function that will return a string representation of a decimal number in any base you want:

    def baseb(n, b):
        e = n//b
        q = n%b
        if n == 0:
            return '0'
        elif e == 0:
            return str(q)
        else:
            return baseb(e, b) + str(q)
    
    >>> baseb(10,3)
    '101'
    

    Better yet, you can use numpy:

    >>> import numpy as np
    >>> np.base_repr(10, 3)
    '101'