[Tutor] Function for converting ints from base10 to base2?
Terry Carroll
carroll at tjc.com
Thu Feb 22 02:17:27 CET 2007
On Tue, 20 Feb 2007, Dick Moores wrote:
> 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 like the approach of mapping hex or octal digits posted by Alan and Bob,
but, not thinking of that, this would be my straightforward approach:
def computeBin(n):
"""converts base10 integer n to base2 b as string"""
if n == 0: return '0'
sign = ['','-'][n<0]
num = abs(n)
seq = []
while (num != 0):
(num, bit) = divmod(num, 2)
seq.append(str(bit))
seq.append(sign)
return ''.join(reversed(seq))
if __name__ == "__main__":
x = 1234567890
assert x == int(computeBin(x),2)
x = -1234567890
assert x == int(computeBin(x),2)
More information about the Tutor
mailing list