converting decimal to binary
Bengt Richter
bokr at oz.net
Sat May 24 03:02:39 EDT 2003
On Fri, 23 May 2003 21:58:13 -0400, "Tim Peters" <tim_one at email.msn.com> wrote:
>[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>.
>
I liked the literal pattern suggested for hex by someone whose name I've forgotten
(I'm obviously using a regex to express it here):
[01][xX][0123456789abcdefABCDEF]+
where the [01] indicated the sign bit to extend leftwards (so e.g., -1 == 1xF)
For binary, the pattern would presumably become
[01][bB][01]+
so 0xA == 0b1010
and -1 == 1b1 == 1b111 == 1b1111 == 1b11111111
[oO] is not so good for octal, though ;-/
@
\_/
Regards,
Bengt Richter
More information about the Python-list
mailing list