Converting an integer to base 2
stephen.boulet at motorola.com
Fri Nov 30 20:50:01 CET 2001
Ah, that explains why int() fails. Thanks.
Meanwhile, I found this recipe on ActiveState's site:
and I adapted it for my situation.
"""Change a decimal to a base-n number.
Up to base-36 is supported without special notation."""
while len(new_num_string) < 8: # want 8 bits, so pad with zeros
new_num_string = '0' + new_num_string
"David R. Smith" wrote:
> int(string, 2) converts the string to the internal representation. You
> told it that the string was base-2, e.g., '101'. '5' is not a valid
> digit in binary.
> Stephen Boulet wrote:
> > I'm trying to convert integers to base 2. Can someone tell me why this
> > doesn't work?
> > >>> int('5', 2)
> > Traceback (most recent call last):
> > File "<pyshell#102>", line 1, in ?
> > int('5', 2)
> > ValueError: invalid literal for int(): 5
> > Thanks.
> > -- Stephen
More information about the Python-list