Naftuli Tzvi Kay Naftuli Tzvi Kay -4 years ago 221
Python Question

Convert base-2 binary number string to int

I'd simply like to convert a base-2 binary number string into an int, something like this:

>>> '11111111'.fromBinaryToInt()

Is there a way to do this in Python?

Answer Source

You use the built-in [int() function][1], and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)

Update: I removed the use of print so the above "code" is now compatible with either, as pointed out in a comment. The documentation link is also just to the current documentation, which is 3.x-aware but since the function exists in 2.x too that's not a big deal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download