Adding Binary Strings in Python
In this class, we write a program for Adding Binary Strings in Python.
For Complete YouTube Video: Click Here
Adding Binary Strings
The reader should have basic knowledge of python programming. Click here.
Take our complete placement course to crack any placement exam. And to improve your programming knowledge.
Q1) Input is given two binary strings of the same length. The program has to do the binary addition and display the added value in string format.
Note: should also display final carry. If carry is one.
Example:
Input:
string1=”1011″
string2=”1110″
Output: “11001”
After understanding the logic of binary addition, the reader should write the code for different length strings.
Logic
To do binary addition. The reader should have a basic understanding of the binary number system.
Here we are considering the initial carry as 0.
The logic we have written is considering three-bit binary addition.
There are four different possibilities with three-bit binary addition.
P1) All three bits are zero’s. The sum value is zero, and the carry bit value is zero.
P2) All three bits are one’s. The sum value is one, and the carry bit value is one.
P3) One bit is having value one, and the remaining bits are zero’s. The sum value is one, and the carry bit value is zero.
P4) Any two bits are one’s, and the remaining is zero. The sum value is zero, and the carry bit value is one.
The above four conditions are written in simple if-else conditions.
The addition starts from the rightmost bit in string1 and string2. And carry is considered as zero.
Each time carry is updated and used as a third input.
Identify the logic used in the below program for better practice.
Program
s1=input("enter your binary string")
s2=input("enter second binary string")
slength=len(s1)
list1=[]
c="0"
for j in range(slength-1,-1,-1):
b1=s1[j]
b2=s2[j]
if b1=="0" and b2=="0" and c=="0":
list1.append("0")
c="0"
elif b1=="1" and b2=="1" and c=="1":
list1.append("1")
c="1"
elif (b1=="1" and b2=="0" and c=="0")or(b1=="0" and b2=="1" and c=="0")or(b1=="0" and b2=="0" and c=="1"):
list1.append("1")
c="0"
else:
list1.append("0")
c="1"
if c=="1":
list1.append("1")
z="".join(list1[::-1])
print(z)