Converting integer to binary representation

Bengt Richter bokr at oz.net
Wed Dec 17 15:57:48 EST 2003


On Wed, 17 Dec 2003 17:39:52 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote:

>anton at vredegoor.doge.nl (Anton Vredegoor) wrote:
>
>> >>> list(10)
>> >>> [True,False,True,False]
>
>Sorry,	I was dead wrong here, or maybe not, it all depends on the
>future.
>
>The code below here would make the positions of the booleans
>correspond to the powers of two: 
>
> >>> list(10)
> >>> [False,True,False,True]
>
>But the other interpretation has some merit too since it corresponds
>to the way we use strings to denote numbers. There is a choice between
>left-to-right and right-to-left here, analogous to the "most
>significant bit" issue.
>
>Because these interpretations are more or less equally valid, there is
>no obvious way of doing it. Making an explicit choice here would be
>good since that would remove the ambiguity. Guido could use his time
>machine to make one of these alternatives the obvious way to do it.
>
IMO little-endian is a better choice. The value of a number in terms of
bits is pretty naturally spelled

    sum([bit*2**pow2 for pow2, bit in enumerate(bitlist)])

i.e.,

 >>> bitlist = [False,True,False,True]
 >>> sum([bit*2**pow2 for pow2, bit in enumerate(bitlist)])
 10

Regards,
Bengt Richter




More information about the Python-list mailing list