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

George Sakkis george.sakkis at gmail.com
Fri Sep 29 02:17:05 EDT 2006


Steve Holden wrote:

> MonkeeSage wrote:
> > So far as unobfuscated versions go, how about the simple:
> >
> > def to_bin(x):
> >   out = []
> >   while x > 0:
> >     out.insert(0, str(x % 2))
> >     x = x / 2
> >   return ''.join(out)
> >
> > Regards,
> > Jordan
> >
>   >>> to_bin(0)
> ''
>
> 6/10: try harder :)

Ok, how about a fast *and* readable version? Works for non-negatives,
but negatives are trivial to add if necessary:

from array import array

def fast2bin(n):
    s = array('c')
    while n>0:
        s.append('01'[n&1])
        n >>= 1
    s.reverse()
    return s.tostring() or '0'

try: import psyco
except ImportError: pass
else: psyco.bind(fast2bin)


George




More information about the Python-list mailing list