python – Convert base-2 binary number string to int

python – Convert base-2 binary number string to int

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

>>> int(11111111, 2)
255

Here is documentation for Python 2, and for Python 3.

Just type 0b11111111 in python interactive interface:

>>> 0b11111111
    255

python – Convert base-2 binary number string to int

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin=11111111)
>>> b.uint
255

Note that the unsigned integer is different from the signed integer:

>>> b.int
-1

The bitstring module isnt a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

Leave a Reply

Your email address will not be published.