convert integer to binary

Bengt Richter bokr at oz.net
Sat May 3 16:20:58 EDT 2003


On 02 May 2003 15:42:21 -0700, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

>ekranawetter at utanet.at (ekranawetter-piber) writes:
>
>> Hi all,
>> 
>> I couldn't find any function in Python to convert integers to binary
>> and vice versa, for example:
>> 
>> integer 16 = bin 10000, or 
>> integer 15 = bin  1111
>> bin 11 = integer 3
>
>Note this doesn't bother stripping leading zeros from the result:
>
>def i2b(n):
>  hdigits = ('0000','0001','0010','0011','0100','0101','0110','0111',
>             '1000','1001','1010','1011','1100','1101','1110','1111')
>
>  a = [hdigits[int(d,16)] for d in hex(n)[2:]]
>  return ''.join(a)

Stripping leading zeroes is easy enough
   return ''.join(a).lstrip('0')

... digs in dustbin... (first bit is explicit 2's complement sign bit here)

 >>> def binstr(n, maxbits=None):
 ...     absn = abs(n)
 ...     s=[chr(((n>>b)&1)+48) for b in xrange(maxbits or len(hex(n))*4)
 ...         if maxbits or not b or absn>>(b-1)]
 ...     s.reverse()
 ...     return ''.join(s)
 ...
 >>> binstr(15)
 '01111'
 >>> binstr(16)
 '010000'
 >>> binstr(-15)
 '10001'
 >>> binstr(-16)
 '110000'
 >>> binstr(-16,32)
 '11111111111111111111111111110000'
 >>> for i in range(-9,10): print binstr(i),
 ...
 10111 11000 1001 1010 1011 1100 101 110 11 0 01 010 011 0100 0101 0110 0111 01000 01001

BTW, len(hex(n))*4 is just to get a sufficient count, not an exact one, so the 'L'
on the end of a long doesn't hurt except a few extra loops in the list comp that don't
add anything.

BTW2, anybody for binary literals of the form sbxxxx, where s is the sign bit as above
and xxxx is the rest? Similar to a proposed hex format of 0xnnnn and 1xnnn to indicate
what sign bit to extend above the bottom bits. Works nicely for unified ints and longs.

Regards,
Bengt Richter




More information about the Python-list mailing list