[Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
don arnold
darnold02 at sprynet.com
Fri Jan 2 12:17:02 EST 2004
----- Original Message -----
From: "Todd G. Gardner" <piir at earthlink.net>
To: "Tutor at Python. Org" <tutor at python.org>
Sent: Friday, January 02, 2004 7:43 AM
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
> Hello everyone,
>
> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85)
>
> Thanks for any pointers,
>
> Todd
The int() function will do the conversion from binary (and other bases)
for you if you supply the optional base parameter:
>>> int('1111111',2)
127
>>> int('001',2)
1
>>> int('17',8)
15
I _thought_ there was a function somewhere to convert an int to a binary
string,
but I couldn't find it. So, here's a function that will convert an int to
string of any
base up to 36:
import string
digits = string.digits + string.ascii_uppercase
def convert(num, base):
res = []
divisor = 1
while num >= divisor * base:
divisor *= base
remainder = num
while divisor >= 1:
index, remainder = divmod(remainder,divisor)
res.append(digits[index])
divisor /= base
res = ''.join(res)
if int(res, base) != num:
raise 'bad conversion!'
return res
if __name__ == '__main__':
while 1:
num = raw_input('number to convert: ')
if num == '':
break
num = int(num)
base = int(raw_input('base : '))
print '%d in base %d is %s' % (num, base, convert(num,base))
print
[example output:]
number to convert: 255
base : 2
255 in base 2 is 11111111
number to convert: 255
base : 16
255 in base 16 is FF
number to convert: 255
base : 10
255 in base 10 is 255
number to convert: 255
base : 8
255 in base 8 is 377
number to convert:
HTH,
Don
More information about the Tutor
mailing list