3 Python Programs to Convert binary to int

Python

In this post, we are going to use different 3 Python programs to convert binary to int by using Python’s built-in function int(), bitstring Module, f-string with code examples.

Python Int() function to Convert binary to int


The Python built-in int() function returns an integer from a string or number. If no argument is passed then it returns 0.

Syntax

int(val=0,base=10)

Parameters

  • val: it can be string or number to be converted to integer object
  • base : It is Base of val( if value is number)it can be 0 or 2-32.

1.Python Program to convert binary to int


In this example, we have a binary string “binary_val” that we have passed to int() function to get the int object. We are printing the result using the print() method

binary_val = "101101"
 
number = int(binary_val, 2)
print(number) 

Output

45

2. bitstring Module to convert binary to int Python


The bitstring bitarray() method can be used to convert binary string to int Python.

Python Program to convert binary to int

from bitstring import BitArray

binary_val = "101101"
 
number =  BitArray(bin=binary_val ).int
print(number)   

Output

45

3. f-string to Convert binary to int Python


Python version 3.6 introduced the formatted string literal also known as “f-string. To use it we have to start the string with “F” or “f” before quotation marks and write a Python expression or variable that contains literal values between { } that are evaluated at runtime. The f-string controls the final output of the formatted string.

Python Program to convert int to binary Using f-string

number =  f'{0b101101:#0}'
print(number)   

Output

45

Summary

In this post, we have learned how to convert binary to int Python using built-in function int(), bitstring Module, f-string with code examples.