converting decimal to binary

Raymond Hettinger vze4rx4y at verizon.net
Fri May 23 21:20:34 EDT 2003


"Michael P. Soulier" <msoulier at storm.ca._nospam> wrote in message
news:slrnbctdki.b9i.msoulier at tigger.digitaltorque.ca...
>     Hey people.
>
>     I'm trying to find a simple way to convert a decimal number to a
> binary string representation. I could do this the hard way, but as it's
> a one-liner in perl, I'm hoping there's an easy way to do this in
> python.
>
> main::(-e:1):   0
>   DB<1> p unpack("B*", pack("C", 192))
> 11000000
>
>     Is there a similar way to do this in Python?


>>> def bin(x):
 d = {0:'000', 1:'001', 2:'010', 3:'011', 4:'100', 5:'101', 6:'110', 7:'111'}
 return ''.join([d[int(dig)] for dig in oct(x)])

>>> bin(192)
'000011000000'


Anything is a one-liner once someone has written a function
that directly supports whatever your trying to do :-)

 There is a trade-off between having builtin support for everything
versus making it trivially easy to craft a new tool for things
like binary conversions which don't seem to come-up that
often.


Raymond Hettinger









More information about the Python-list mailing list