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 from unwind on Stack OverflowYou 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
Convert Binary String into Integer (Python) - Stack Overflow
Python 3, Converting a string storing binary data to Int - Stack Overflow
Convert int to binary string in Python - Stack Overflow
Function that converts binary to string explanation?
It works fine when you remove all the typos and indentation problems:
def binStrToInt(binary_str):
"""The function binStrToInt() takes in one input, a string of ones and
zeros (no spaces) called BINARY_STR. It treats that input as a binary
number (base 2) and converts it to a decimal integer (base 10). It
returns an integer result."""
length = len(binary_str)
num = 0
for i in range(length):
num = num + int(binary_str[i])
num = num * 2
return num / 2
But honestly, how did you not see these? The interpreter tells you about most of them (all except the return indentation). And as commenters have mentioned, the built-in int() function will do the same thing if you pass it a string, and the number 2 to cause it to convert from a binary string.
EDIT Based on your comment below, you are somehow using a special quote, perhaps copied from a web-page or something. That won't work -- here is an example of something that worked and something that didn't in the interpreter:
>>> def binStrToInt(binary_str):
... length = len(binary_str)
... num = 0
... for i in range(length):
... num = num + int(binary_str[i])
... num = num * 2
... return num / 2
...
>>> binStrToInt('101')
5
>>> binStrToInt(โ101โ)
File "<stdin>", line 1
binStrToInt(โ101โ)
^
SyntaxError: invalid syntax
You could make the logic a bit more easy to understand if you can re-write your code as
num = 0
for i in range(len(binary_str)):
num = num * 2
num = num + int(binary_str[i])
return num