views:

819

answers:

7

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 , BASE ) , BASE ) == X 

the function name/argument order is unimportant

For any number X and base BASE that int() will accept.

This is an easy function to write -- in fact 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:

  • Those functions are not available on older versions of python with which I need compatibility (2.2)
  • I want a general solution that can be called the same way for different bases
  • I want to allow bases other than 2,8,16

Related

A: 

Python doesn't have a built-in function for printing an integer in an arbitrary base. You'll have to write your own if you want to.

Mike Graham
A: 

http://code.activestate.com/recipes/65212/

def base10toN(num,n):
    """Change a  to a base-n number.
    Up to base-36 is supported without special notation."""
    num_rep={10:'a',
         11:'b',
         12:'c',
         13:'d',
         14:'e',
         15:'f',
         16:'g',
         17:'h',
         18:'i',
         19:'j',
         20:'k',
         21:'l',
         22:'m',
         23:'n',
         24:'o',
         25:'p',
         26:'q',
         27:'r',
         28:'s',
         29:'t',
         30:'u',
         31:'v',
         32:'w',
         33:'x',
         34:'y',
         35:'z'}
    new_num_string=''
    current=num
    while current!=0:
        remainder=current%n
        if 36>remainder>9:
            remainder_string=num_rep[remainder]
        elif remainder>=36:
            remainder_string='('+str(remainder)+')'
        else:
            remainder_string=str(remainder)
        new_num_string=remainder_string+new_num_string
        current=current/n
    return new_num_string

Here's another one from the same link

def baseconvert(n, base):
    """convert positive decimal integer n to equivalent in another base (2-36)"""

    digits = "0123456789abcdefghijklmnopqrstuvwxyz"

    try:
        n = int(n)
        base = int(base)
    except:
        return ""

    if n < 0 or base < 2 or base > 36:
        return ""

    s = ""
    while 1:
        r = n % base
        s = digits[r] + s
        n = n / base
        if n == 0:
            break

    return s
gnibbler
+6  A: 
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and  "0" ) or ( baseN(num // b, b, numerals).lstrip("0") + numerals[num % b])

ref: http://code.activestate.com/recipes/65212/

jellyfishtree
`//` will **not** work in Python 2.2 ...
Alex Martelli
Elegant in its brevity. It seems to work under python 2.2.3 for non-negative integers. A negative number infinitely recurses.
Mark Borgerding
+6  A: 

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 fuction, 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., most simply:

import string
digs = string.digits + string.lowercase

def int2base(x, base):
  if x < 0: sign = -1
  elif x==0: return '0'
  else: sign = 1
  x *= sign
  digits = []
  while x:
    digits.append(digs[x % base])
    x /= base
  if sign < 0:
    digits.append('-')
  digits.reverse()
  return ''.join(digits)
Alex Martelli
A: 
>>> import string
>>> def int2base(integer, base):
        if not integer: return '0'
        sign = 1 if integer > 0 else -1
        alphanum = string.digits + string.ascii_lowercase
        nums = alphanum[:base]
        res = ''
        integer *= sign
        while integer:
                integer, mod = divmod(integer, base)
                res += nums[mod]
        return ('' if sign == 1 else '-') + res[::-1]


>>> int2base(-15645, 23)
'-16d5'
>>> int2base(213, 21)
'a3'
SilentGhost
+2  A: 
Mark Borgerding
How do you convert the base64 output of our function back to an integer?
detly
+1  A: 
"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144