convert integer to binary

Scott David Daniels scott.daniels at acm.org
Fri May 9 12:11:57 EDT 2003


As long as we are fiddling:

Paul Rubin wrote:
> ekranawetter at utanet.at (ekranawetter-piber) writes:
>>I couldn't find any function in Python to convert integers to binary
> 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)

def i2b(n):
     """Convert an integer to its binary text representation"""
     if n <= 0:
         if n < 0:
             return '-' + i2b(-n)
         return '0'
     octaldigits = '000','001','010','011','100','101','110','111'
     octaltext = oct(n).rstrip('L')
     a = [octaldigits[int(digit)] for digit in octaltext]
     return ''.join(a).lstrip('0')

if __name__ == '__main__':
     assert map(i2b, [0,1,2,4,8,  16,   32,   21L, 3L, -2, -5L]) == (
               '0 1 10 100 1000 10000 100000 10101 11 -10 -101'.split())

-Scott David Daniels
Scott.Daniels at Acm.Org





More information about the Python-list mailing list