Convert base-2 binary number string to int
Solution 1:
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.
Solution 2:
Just type 0b11111111 in python interactive interface:
>>> 0b11111111
255
Solution 3:
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 isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
Solution 4:
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])