converting decimal to binary

Markus Wankus markus_wankus at hotmail.com
Sat May 24 00:38:06 EDT 2003


On 24 May 2003 03:19:49 GMT, Michael P. Soulier <msoulier at storm.ca._nospam> 
wrote:

> On Sat, 24 May 2003 01:20:34 GMT, Raymond Hettinger
> <vze4rx4y at verizon.net> wrote:
>>
>>>>> 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.
>
> True, true. I'm a fan of adding whatever we need to the standard
> library, as long as it stays out of the core language. Keep that simple.
>
> I did things the hard way, so now I have a one-liner.
>
> def byte2bits(byte):
> """This function takes a single integer, representing a single byte 
> value,
> and returns a bit-string representing that byte."""
> assert(byte < 256 and byte >= 0)
> bits = ""
> power = 7
> while power >= 0:
> exponential = 2 ** power
> if byte >= exponential:
> bits += '1'
> byte -= exponential
> else:
> bits += '0'
>
> power -= 1
>
> assert(len(bits) == 8)
> return bits
>
> I wanted to ensure 8 bits returned, as this is for network
> calculations. That's a clever solution of yours though.
>
> Mike
>

I have always liked the one in the cookbook for base conversion:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286

A sweet solution that you can extend easily.


-- 
Markus




More information about the Python-list mailing list