Problem: Write a program in Python to add two binary numbers and output the sum.

In Python, we can add two binary numbers using the following syntax:

sum = int(binary_1, 2) + int(binary_2, 2)

where binary_1 and binary_2 are two binary numbers in string format.

The int() function converts the string into an integer of the specified base. If we pass 2 as the second parameter to int(), we get the binary number as the return result.

The base of the binary number system is 2, whereas the base of the decimal number system is 10.

Here is an example of adding two binary numbers in Python:

binary_1 = '10010'
binary_2 = '11111'

sum = int(binary_1, 2) + int(binary_2, 2)
sum = bin(sum)

print(sum)

Output:

0b110001

In the above example, we are converting the string formatted numbers into binary numbers and then adding them.

Since the addition in Python returns an integer of base 10 (i.e. decimal), we need to convert it to a base 2 number system (i.e. binary) using the bin() function.

This Post Has 3 Comments

  1. Hima

    The output should be in 110001 not in ob11001 is it possible to get that output?

  2. yash

    print(str(sum)[2:] ) is not working

Leave a Reply