Addition of Two Binary Number in Python
In the following program, we are going to use two built-in functions int() and bin() for the addition of two binary numbers in Python programming.
The int() function converts a string into an integer number considered given base value.
a = '0011' print(int(a,2))
Addition of Two Binary Number
Method 1: Naive Approach
1. Declare the variables a and b
2. add zeros at the beginning of the shorter string until it reaches the longer string. The zfill() method is used to add zeros at the beginning of the string until it reaches the specified length.
3. Then start from the last characters of the two binary strings and add them one by one.
4. If the sum becomes more than 1, then store carry for the next digits.
5. Finally, return the result
a = "1101" b = "100" max_len = max(len(a), len(b)) a = a.zfill(max_len) b = b.zfill(max_len) result = '' carry = 0 for i in range(max_len - 1, -1, -1): temp = carry temp += 1 if a[i] == '1' else 0 temp += 1 if b[i] == '1' else 0 result = ('1' if temp % 2 == 1 else '0') + result carry = 0 if temp < 2 else 1 if carry != 0: result = '1' + result print("The addition of a and b is ", result.zfill(max_len))
The addition of a and b is 10001
Method 2: Using inbuilt function
1. Firstly, convert the binary strings to a decimal using int() function.
2. Then add them.
3. Finally, covert results into a binary number using bin() function.
a = '0011' # decimal value is 3 b = '1010' # decimal value is 10 result = bin(int(a,2) + int(b,2)) print("Addition of the a and b is ",result)
Addition of the a and b is 0b1101