Converting an integer base 10 to a binary number

Alex Martelli aleaxit at yahoo.com
Thu Mar 29 07:02:29 EST 2001


"Peter Stöhr" <peter.stoehr at fh-hof.de> wrote in message
news:3AC1E898.D5929C44 at fh-hof.de...
"""
I know the int(x[,radix]) function that converts a string or a number
(for a give radix) to an integer. Is there a built-in function that
provides a conversion the other way round?
Something like
    bin(32) = "10000"
"""

There is no 'bin' built-in function -- you have to roll your own, e.g:

trits = ('000','001','010','011','100','101','110','111')
from string import octdigits as o

def nol0(s):
    for i in range(0, len(s)):
        if s[i]!='0': return s[i:]
    return '0'

def bin(n):
    return nol0(''.join([trits[o.find(x)] for x in oct(n)]))


Alex






More information about the Python-list mailing list