Convert Binary to Int in Python

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
print(a)

Output:

5

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)
print(a)

Output:

5

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:

print(f'{0b101:#0}')

Output:

5

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
    print(int_val) 
    

binary2int(101)

Output:

5
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Binary

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

  • Convert Int to Binary in Python
  • Convert Roman Numerals to Integers in Python
  • Convert Integer to Roman Numerals in Python
  • Integer Programming in Python
  • Convert Boolean Values to Integer in Python
  • Convert String to Integer in Python