[Tutor] Integer to binary
Dick Moores
rdm at rcblue.com
Tue Jul 10 17:38:18 CEST 2007
At 07:27 AM 7/10/2007, Mihai Iacob wrote:
>Hello,
>
>Is there a function that converts from integer to
>binary (or a module that handles this)?
>
>The only thing close to it that i found in the manual
>is the binascii module but i can't get it to work.
Here's one:
def base10ToBaseN(n, base=2):
"""converts base 10 integer n to base 2-9 integer as string"""
if n == 0: return '0'
sign = '-' if n<0 else ''
num = abs(n)
seq = []
while (num != 0):
(num, bit) = divmod(num, base)
seq.append(str(bit))
seq.append(sign)
return ''.join(reversed(seq))
Dick Moores
More information about the Tutor
mailing list