# Converting an integer to base 2

Stephen Boulet 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:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65212

and I adapted it for my situation.

def decimalToN(num,n=2):
"""Change a decimal to a base-n number.
Up to base-36 is supported without special notation."""

new_num_string=''
current=num
while current!=0:
remainder=current%n
if remainder>=36:
remainder_string='('+str(remainder)+')'
else:
remainder_string=str(remainder)
new_num_string=remainder_string+new_num_string
current=current/n
while len(new_num_string) < 8:  # want 8 bits, so pad with zeros
new_num_string = '0' + new_num_string
return 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

```