Converting an integer base 10 to a binary number

Stolker, Wim w.t.stolker at getronics.com
Fri Mar 30 02:43:09 EST 2001


I don't know of a built-in, or 'batteries included' function
but:

def tobase(b,n,result=''):
    if n == 0:
        if result:
            return result
        else:
            return '0'
    else:
        return tobase(b,n/b,str(n%b)+result)

or, more safe and complete:

def tobase(base,number):
    global tb
    def tb(b,n,result=''):
        if n == 0: return result
        else: return tb(b,n/b,str(n%b)+result)

    if type(base) != type(1):
        raise TypeError, 'invalid base for tobase()'
    if base <= 0:
        raise ValueError, 'invalid base for tobase(): %s' % base
    if type(number) != type(1) and type(number) != type(1L):
        raise TypeError, 'tobase() of non-integer'
    if number == 0:
        return '0'
    if number > 0:
        return tb(base, number)
    if number < 0:
        return '-' + tb(base, -1*number)

bin = lambda n: tobase(2,n)

does what you want.

Wim


-----Original Message-----
From: Peter Stöhr [mailto:peter.stoehr at fh-hof.de]
Sent: Wednesday, March 28, 2001 3:35 PM
To: python-list at python.org
Subject: Converting an integer base 10 to a binary number


Hi out there,

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"

Thanks in advance
    Peter
-- 
Fachhochschule Hof
Prof. Dr. Peter Stöhr				Tel: 09281 - 409 485
Alfons-Goppel-Platz 1				Fax: 09281 - 409 477
95028 Hof / Germany




More information about the Python-list mailing list