How to convert base 10 to base 2?
Benjamin Kaplan
benjamin.kaplan at case.edu
Mon Aug 20 04:04:22 EDT 2012
On Mon, Aug 20, 2012 at 12:50 AM, <gianpycea at gmail.com> 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)
'0b1100'
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))
'0b101'
Although you don't need to specify the 10 because that's the default.
>>> bin(int('5'))
'0b101'
More information about the Python-list
mailing list