Convert a binary string to an integer in Python
This post will discuss how to convert a binary string to an integer in Python.
1. Using int() function
The standard way to convert a binary string to an integer is using the built-in function int. You need to pass base 2 for a binary number.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': b = "01001111" x = int(b, 2) print(x) # 79 |
2. Using bitstring module
Another alternative is to use the bitstring module, as shown below:
|
1 2 3 4 5 6 7 8 9 |
from bitstring import BitArray if __name__ == '__main__': b = "01001111" x = BitArray(bin=b).int print(x) # 79 |
That’s all about converting a binary string to an integer in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)