Python Program to calculate the sum of two binary numbers

How to add the binary numbers in python?

In this python program, we have to find the sum of two Binary numbers. It is a beginner python program. We have two challenges in finding the sum of two binary numbers in the python programming language.

  • The first is to convert the string into the binary providing the base value in the int datatype. We are converting the binary string value to a decimal using the int data type with a base value as 2.
  • We do the addition of the numbers in python, and again we have to convert the sum from decimal to binary using a bin function.

The program is simple, but it confusing; 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.

ALGORITHM

STEP 1: We give the binary numbers 1 and 2 and store the value in num1 and num2 as a binary string.

STEP 2: We are finding the sum using two functions as a bin and int data type. Here we use the int data type of base 2 for converting the binary string input to decimal. We do the sum of two decimal numbers and use the bin function to convert the sum variable from decimal to binary.

STEP 3: Print the sum as a binary value.

Python Source Code

                                          num1 = '00001'  # 1

num2 = '10001'  #17

sum = bin(int(num1,2) + int(num2,2))            # we use int data type with base 2 and bin function to convert the binary string in python programming  to decimal and convert the sum from decimal to binary 

print(sum)           # print the sum 
                                      

OUTPUT

0b10010