converting decimal to binary

Tim Peters tim_one at email.msn.com
Fri May 23 21:58:13 EDT 2003


[Michael P. Soulier]
>>     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.

[Raymond Hettinger]
> >>> 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.

OTOH, there's curious asymmetry here:

>>> int('00011000000', 2)
192
>>>

That is, "the other direction" is built in.  Greg Wilson was keen to
generalize this in both directions but I don't think it ever got written up
in a PEP.  Maybe a patch is sitting on SourceForge.  It's regrettable (IMO)
that Python aped C's bizarre mishmash of spellings for non-decimal literals.
Sometimes I'd like binary literals too (making sense of a bitmask in hex or
octal is a PITA -- only a computer weenie can look at 0xa and *see* an
alternating pattern of 0s and 1s).

All in all, I'm happier we implemented generators, though <wink>.






More information about the Python-list mailing list