The Python Oracle

Convert base-2 binary number string to int

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Question
00:25 Accepted answer (Score 898)
00:47 Answer 2 (Score 47)
01:03 Answer 3 (Score 35)
01:34 Answer 4 (Score 10)
02:07 Thank you

--

Full question
https://stackoverflow.com/questions/8928...

Accepted answer links:
[Python 2]: https://docs.python.org/2/library/functi...
[Python 3]: https://docs.python.org/3/library/functi...

Answer 3 links:
[bitstring]: https://pypi.org/project/bitstring/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 963


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.




ANSWER 2

Score 55


Just type 0b11111111 in python interactive interface:

>>> 0b11111111
    255



ANSWER 3

Score 39


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 (uint) is different from the signed integer (int):

>>> b.int
-1

Your question is really asking for the unsigned integer representation; this is an important distinction.

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.




ANSWER 4

Score 10


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))])