Can string formatting be used to convert an integer to its binary form ?

Paul Rubin http
Fri Sep 29 02:12:50 EDT 2006


"MonkeeSage" <MonkeeSage at gmail.com> writes:
> def to_bin(x):
>   out = []
>   while x > 0:
>     out.insert(0, str(x % 2))
>     x = x / 2
>   return ''.join(out)

That returns the empty string for x=0.  I'm not sure if that's a bug
or a feature.

It also returns the empty string for x < 0, probably a bug.

It will break in Python 3, where 1 / 2 == 0.5.

Here's yet another version:

def to_bin(n):
    if n < 0: return '-' + to_bin(-n)
    if n==0: return '0'
    return ''.join(
            ("0000", "0001", "0010", "0011",
            "0100", "0101", "0110", "0111",
            "1000", "1001", "1010", "1011",
            "1100", "1101", "1110", "1111",)[int(d,16)] \
            for d in '%x'%n).lstrip('0')



More information about the Python-list mailing list