How to convert base 10 to base 2?

Joel Goldstick joel.goldstick at gmail.com
Mon Aug 20 13:57:59 EDT 2012


On Mon, Aug 20, 2012 at 1:29 PM, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> On Mon, 20 Aug 2012 16:52:42 +0200, Jean-Michel Pichavant
> <jeanmichel at sequans.com> declaimed the following in
> gmane.comp.python.general:
>
>> note that the builtin bin function is not available with python ver < 2.6
>>
>> def Denary2Binary(n):
>>     '''convert denary integer n to binary string bStr'''
>>     bStr = ''
>>     if n < 0:  raise ValueError, "must be a positive integer"
>>     if n == 0: return '0'
>>     while n > 0:
>>         bStr = str(n % 2) + bStr
>>         n = n >> 1
>>     return bStr
>>
>> JM
>>
>> (not my function but I can't remember who I stole from)
>
>         I think I typically have done this by going through a hex
> representation.
>
> H2B_Lookup = {  "0" : "0000",   "1" : "0001",
>                                         "2" : "0010",   "3" : "0011",
>                                         "4" : "0100",   "5" : "0101",
>                                         "6" : "0110",   "7" : "0111",
>                                         "8" : "1000",   "9" : "1001",
>                                         "A" : "1010",   "B" : "1011",
>                                         "C" : "1100",   "D" : "1101",
>                                         "D" : "1110",   "F" : "1111"    }
>
> def I2B(i):
>     sgn = " "
>     if i < 0:
>         sgn = "-"
>         i = -i
>     h = ("%X" % i)
>     return sgn + "".join([H2B_Lookup[c] for c in h])
>
>>>> from i2b import I2B
>>>> I2B(10)
> ' 1010'
>>>> I2B(1238)
> ' 010011100110'
>>>> I2B(-6)
> '-0110'
>>>>
> --
>         Wulfraed                 Dennis Lee Bieber         AF6VN
>         wlfraed at ix.netcom.com    HTTP://wlfraed.home.netcom.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list

This may be moving off topic, but since you encode -6 as -0110 I
thought I'd chime in on 'two's complement'

with binary number, you can represent 0 to 255 in a byte, or you can
represent numbers from 127 to -128.  To get the negative you
complement each bit (0s to 1s, 1s to 0s), then add one to the result.
So:
3 -->    00000011
~3 ->   111111100
add 1               1
result   111111101

The nice thing about this representation is that arithmetic works just
fine with a mixture of negative and positive numbers.

eg 8 + (-3) ----> 00001000
                       111111101
gives:               00000101
which is 5!

-- 
Joel Goldstick



More information about the Python-list mailing list