Python - How To Convert Binary to Int in Python

ID : 437

viewed : 157

Tags : PythonPython BinaryPython Integer

vote vote

92

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 

  • Related HOW TO?