Python Program to calculate the sum of two binary numbers

February 8, 2022, Learn eTutorial

How to add two binary numbers in python?

In this python program, we have to find the sum of two binary numbers. We have two challenges in finding the sum of two binary numbers.

  • The first is to convert the binary string value to a decimal using the int() datatype with a base value of 2.
  • We do the addition of the numbers, and again we have to convert the sum from decimal to binary using a bin function.

The program is simple, the steps are: 

  • Convert the binary string to decimal.
  • Calculate the sum.
  • Convert the sum from decimal to binary.

We are accepting the num1 and num2 as predefined, and we use the variable sum for storing the result of the addition of these two variables using the int function and bin function.


STEP 1: Read the binary numbers to num1 and num2 as a binary string.

STEP 2: We are finding the sum using two built-in functions bin() and int(). Here we use the int() of base 2 for converting the binary string input to decimal. After converting to decimal numbers do the addition of two numbers and use the bin() function to convert the sum of decimal value to binary.

STEP 3: Print the result sum of the binary value.

Python Source Code

                                          num1=input("Enter 1st binary number ")
num2=input("Enter 2nd binary number ")

sum = bin(int(num1,2) + int(num2,2))[2:]

print("Sum is ",sum)           # print the sum 


Enter 1st binary number 10100
Enter 2nd binary number 11001
Sum is  101101