converting decimal to binary

Bengt Richter bokr at oz.net
Sun May 25 06:36:48 EDT 2003


On 24 May 2003 14:32:00 -0700, danb_83 at yahoo.com (Dan Bishop) wrote:

>bokr at oz.net (Bengt Richter) wrote in message news:<ban5ef$fq$0 at 216.39.172.122>...
>
>> 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)
>
>But how will that work after int/long unification?

Beautifully ;-)

The extension leftwards is to an infinite number of bits, but the canonical _representation_
is any convenient chunk whose most significant bit is in the extended bits. For int, that's
32 or 64 bits, for long it may be some multiple of 15 bits, but in a unified integer there
is no width except that a representation requires a minimum of 1 bit and has to include
enough to represent the number, with at least one sign bit being canonical, but allowing the
sign to extend as convenient to say k*8 or k*15 or k*32 etc bits. For N total bits expressed as
a list of 1 or 0 values, listed most significant first (for readability here) including
the sign bit at bits[0], the numerical value would be 

 >>> def bitsval(bits):
 ...     return reduce(lambda sum,bit: sum*2L+bit, bits[1:], 0L) - bits[0]*2L**(len(bits)-1)
 ...
 >>> bitslist = [[0], [0,1], [0,0,1], [1], [1,1], [1,1,1], [1,0,1,0], [1,1,1,1,1,0,1,0], [0,1,1,0]]
 >>> for bits in bitslist:
 ...     print '%25s => %3s' % (bits, bitsval(bits))
 ...
                       [0] =>   0
                    [0, 1] =>   1
                 [0, 0, 1] =>   1
                       [1] =>  -1
                    [1, 1] =>  -1
                 [1, 1, 1] =>  -1
              [1, 0, 1, 0] =>  -6
  [1, 1, 1, 1, 1, 0, 1, 0] =>  -6
              [0, 1, 1, 0] =>   6

obviously it is easy to go from '1b010' to [1, 0, 1, 0] with something like

 >>> def b2bits(bs): return [int(bs[0])] + map(int,bs[2:])
 ...
 >>> b2bits('1b010')
 [1, 0, 1, 0]

and from there via bitsval to the value. (Above is not necessarily a recommended implementation,
just a demo of concept).

Regards,
Bengt Richter




More information about the Python-list mailing list