tags:

views:

155

answers:

2

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...

+1  A: 
def to_base_5(n):
    s=[]
    while n:
        s.append(str(n%5))
        n=n/5
    return ''.join(s[::-1])

For smallish numbers (so the string catenation doesn't bog down) you can use this

def to_base_5(n):
    s=""
    while n:
        s=str(n%5)+s
        n=n/5
    return s
gnibbler
A: 

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
cool. Works for radix <= 10. if you replace %d with %x, works for radix <= 16.
GregS