Convert Binary to Int in Python

In the world of Computer Science, we deal with binary and decimal integer values very frequently. Binary values have a base of 2, and decimal values have a base of 10.

In this tutorial, we will learn how to convert binary to integer in Python.

In Python, binary values are represented by prefixing 0b before the binary representation. It automatically converts the binary to an integer value, as shown below:

a = 0b101



The int function can also achieve the same result. We need to pass the number and its base to convert it into an integer (remember, the base for binary values is 2).

a = int('101',2)



The fstrings in the recent versions of Python is a new and efficient way of formatting strings. We can use them to carry out such binary to integer conversions as shown below:




Here 0b101 is the binary number, and #0 is used to specify that it is to be converted to a decimal value.

We can also create a small user-defined function also for converting a binary value to an integer. The following code snippet shows how:

def binary2int(binary): 
    int_val, i, n = 0, 0, 0
    while(binary != 0): 
        a = binary % 10
        int_val = int_val + a * pow(2, i) 
        binary = binary//10
        i += 1



DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Binary

  • Convert a String to Binary in Python
  • Related Article - Python Integer

  • Convert List of Strings to Integer in Python
  • Convert a Character to an Integer and Vice Versa in Python