int 2 binary: What do you think?

Andrew Gaul gaul at spam.utexas.edu
Thu May 10 09:08:28 EDT 2001


In article <3ae42b7a.4988661 at news.muenster.de>, Martin Bless wrote:
>I needed to convert integers to binary representation and couldn't
>find a builtin function. So here's what I came up with. The idea is to
>return a string as short as possible and have positive numbers always
>start with a  "0".
>
>I wonder if there's a better way? 

Here's a shorter implementation; it may be more efficient:

def bin(i):
    l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
         '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
    s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:]))
    if s[0] == '1' and i > 0:
        s = '0000' + s
    return s

It'd be nice if an equivalent built-in function was added in a future
version of Python.

-- 
     | a | n | d | r | e | w | @ | g | a | u | l | . | o | r | g |
                      White trash.  Loser.  Geek.



More information about the Python-list mailing list