pythonradix

How to convert an integer to a string in any base?


Python allows easy creation of an integer from a string of a given base via

int(str, base). 

I want to perform the inverse: creation of a string from an integer, i.e. I want some function int2base(num, base), such that:

int(int2base(x, b), b) == x

The function name/argument order is unimportant.

For any number x and base b that int() will accept.

This is an easy function to write: in fact it's easier than describing it in this question. However, I feel like I must be missing something.

I know about the functions bin, oct, hex, but I cannot use them for a few reasons:

Related


Solution

  • If you need compatibility with ancient versions of Python, you can either use gmpy (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions – you may need to try older releases since the recent ones have not been tested for venerable Python and GMP releases, only somewhat recent ones), or, for less speed but more convenience, use Python code – e.g., for Python 2, most simply:

    import string
    digs = string.digits + string.ascii_letters
    
    
    def int2base(x, base):
        if x < 0:
            sign = -1
        elif x == 0:
            return digs[0]
        else:
            sign = 1
    
        x *= sign
        digits = []
    
        while x:
            digits.append(digs[int(x % base)])
            x = int(x / base)
    
        if sign < 0:
            digits.append('-')
    
        digits.reverse()
    
        return ''.join(digits)
    

    For Python 3, int(x / base) leads to incorrect results, and must be changed to x // base:

    import string
    digs = string.digits + string.ascii_letters
    
    
    def int2base(x, base):
        if x < 0:
            sign = -1
        elif x == 0:
            return digs[0]
        else:
            sign = 1
    
        x *= sign
        digits = []
    
        while x:
            digits.append(digs[x % base])
            x = x // base
    
        if sign < 0:
            digits.append('-')
    
        digits.reverse()
    
        return ''.join(digits)