How to convert base 10 to base 2?

Benjamin Kaplan benjamin.kaplan at
Mon Aug 20 10:04:22 CEST 2012

On Mon, Aug 20, 2012 at 12:50 AM,  <gianpycea at> wrote:
> Hi,
> as you can argue from the subject, i'm really,really new to python.
> What is the best way to achieve that with python? Because the syntax int('30',2) doesn't seem to work!

That syntax goes the other way- from a string representing a number in
the given base into an integer (which doesn't have a base, although
it's stored in base 2).

You get the binary by doing bin(x), where x is an integer.

>>> bin(12)

If you want to go from a string in base-10 to a string in base-2, you
have to do the conversion to integer first.

>>> bin(int('5',10))

Although you don't need to specify the 10 because that's the default.
>>> bin(int('5'))

More information about the Python-list mailing list