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

MonkeeSage MonkeeSage at gmail.com
Fri Sep 29 08:36:42 CEST 2006


Steve Holden wrote:
>   >>> to_bin(0)
> ''

Doh! Oh, yeah...that! ;)

OK...

def to_bin(x):
  out=[]
  while x > 0:
    out.insert(0, str(x % 2))
    x /= 2
  else:
    out.append(str(x))
  return ''.join(out)

Regards,
Jordan




More information about the Python-list mailing list