# [Tutor] Function for converting ints from base10 to base2?

Dick Moores rdm at rcblue.com
Wed Feb 21 05:47:28 CET 2007

I was surprised to be unable to find a function in Python for
converting ints from base10 to base2. Is there one?

I wrote one, but have I reinvented the wheel again? (Even if I have,
it was an interesting exercise for me.)

I know some of you CS people won't like what I do with negative ints,
but I wanted it this way. On other points than that, I'd appreciate
criticism/suggestions.

===========================================================
def computeBin(n):
"""converts base10 integer n to base2 b as string"""
from math import log, floor
sign = ''
if n == 0:
b = '0'
else:
if n < 0:
sign = "-"
n = -n
e = int(floor(log(n,2)))
b = '1'

for x in range(e):
r = n % 2**e
if r >= 2**(e-1):
b += '1'
else:
b += '0'
e -= 1
return sign + b

def printResult(n,b):
print "%d is %s" % (n, b)

def confirmResult(n,b):
print "Confirming using int():"
print "int(%s,2) is %s" % (b, int(b,2))

if __name__ == '__main__':
n = 1234567890
b = computeBin(n)
printResult(n,b)
confirmResult(n,b)
==============================================

Dick Moores