5

Possible Duplicate:
convert integer to a string in a given numeric base in python

I want to work with base 5 numbers, or any other non standard base for that matter.

I found out int('123', 5) works, but I need to go the other way around.

Should I write my own number class to accomplish this?

Maybe I'm just thinking in the wrong direction...

Community
  • 1
  • 1
Pepijn
  • 4,145
  • 5
  • 36
  • 64
  • 1
    Dupe: http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python – kennytm Feb 18 '10 at 12:20

2 Answers2

6
def to_base_5(n):
    s = ""
    while n:
        s = str(n % 5) + s
        n /= 5
    return s
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

I had fun with this a while ago for a python-dev thread. The original post can be found at http://mail.python.org/pipermail/python-dev/2006-January/059925.html This particular algorithm can perform floating point bases as well.

#!/usr/bin/env python
import math

def ibase(n, radix=2, maxlen=None):
    r = []
    while n:
        n,p = divmod(n, radix)
        r.append('%d' % p)
        if maxlen and len(r) > maxlen:
            break
    r.reverse()
    return ''.join(r)

def fbase(n, radix=2, maxlen=8):
    r = []
    f = math.modf(n)[0]
    while f:
        f, p = math.modf(f*radix)
        r.append('%.0f' % p)
        if maxlen and len(r) > maxlen:
            break
    return ''.join(r)

def base(n, radix, maxfloat=8):
    if isinstance(n, float):
        return ibase(n, radix)+'.'+fbase(n, radix, maxfloat)
    elif isinstance(n, (str, unicode)):
        n,f = n.split('.')
        n = int(n, radix)
        f = int(f, radix)/float(radix**len(f))
        return n + f
    else:
        return ibase(n, radix)

if __name__=='__main__':
    pi = 3.14
    print 'pi:', pi, 'base 10'

    piBase3 = base(pi, 3)
    print 'pi:', piBase3, 'base 3'

    piFromBase3 = base(piBase3, 3)
    print 'pi:', piFromBase3, 'base 10 from base 3'
Shane Holloway
  • 7,550
  • 4
  • 29
  • 37