I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt() 255
Is there a way to do this in Python?
To convert binary integer to decimal, start from the left. Take your current total, multiply it by two and add the current digit. Continue until there are no more digits left. Here is an example of such conversion using the fraction 1011.
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With