Integer to Binary string

Bengt Richter bokr at oz.net
Fri Dec 6 19:47:49 EST 2002


On 6 Dec 2002 08:39:27 -0800, srijit at yahoo.com wrote:

>I would like to know the most efficient Pythonic way to convert an
>integer to a binary string. Any suggestions?
>Is there any Python function similar to _itoa?
>
You can make binary conversion real quick:

 >>> def i2b(i, h2b= dict(zip('0123456789abcdef',
 ...     ['%s%s%s%s' % (e,f,t,o) for e in '01' for f in '01' for t in '01' for o in '01']))):
 ...     return ''.join([h2b[x] for x in hex(i)[2:]]).lstrip('0')
 ...
 >>> for i in range(33): print i2b(i),
 ...
  1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011 10100 
 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110 11111 100000

Doesn't handle longs and may not handle negative the way you'd like though.
But you can fix it to taste, as an exercise ;-)  Above requires 2.2.2.

Regards,
Bengt Richter



More information about the Python-list mailing list