Converting an integer base 10 to a binary number

François Granger francois.granger at free.fr
Fri Mar 30 17:51:04 EST 2001


Peter Stöhr <peter.stoehr at fh-hof.de> wrote:

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

Not fully polished, but works

# python
"""
create the binary rep of an integer as a string of '0' & '1'
20010302    v 1.0
"""
def toBin(x):
    a = ''
    y = x
    while x:
        x, y = x / 2, y % 2
        if y:
            a = '1' + a
        else:
            a = '0' + a
        y = x
    return a

if __name__ == '__main__'
    l = [1, 2, 3, 4, 8, 16, 32, 64, 128, 255, 512, 1024, 2048, 4096,
8192, 16384, 32768]
    for x in l:
        print toBin(x)


-- 
Une faq de frj: http://faq.jardin.free.fr/, près de l'encyclopédie
http://nature.jardin.free.fr/
MacPython beginners http://francois.granger.free.fr/MacPython/faq/



More information about the Python-list mailing list