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

George Sakkis george.sakkis at gmail.com
Fri Sep 29 00:39:49 EDT 2006


Gabriel Genellina wrote:

> At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
>
> >How about this: (where n is the integer you want to convert):
> >
> >     "".join([["0", "1"][(1 << i & n) != 0] for i in
> > range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])
>
> Uhm... so to generate a binary string you have to import the math
> module, convert the integer to float, compute a non-standard
> logarithm, and then...
> What if n<=0?
> Too much, don't you think? :)

Having recently discovered the joy of obfuscated python thanks to the
Code Golf challenges, here's the shortest non-recursive function I came
up with (all integers, signed):

f=lambda n:'-'[:n<0]+''.join(str(m&1)for m in iter(
  lambda x=[abs(n)]:(x[0],x.__setitem__(0,x[0]>>1))[0],0))[::-1]or'0'

Any takers ? ;-)

George




More information about the Python-list mailing list