In this Python tutorial, I will see how to add two binary numbers in Python. What are the different methods needed to add two binary in Python? In the process, we will also see what are binary numbers.
Binary numbers play an essential role in the realm of computing. Every piece of data we interact with is fundamentally represented as binary behind the scenes. But how do binary numbers work in Python, especially when it comes to operations like addition?
A binary number is a number expressed in the base-2 numeral system, which uses only two binary digits, 0 and 1.
The Basics of Binary Addition
Before we proceed, let’s cover some basics. Binary addition is not much different from decimal addition. Here are a few rules to remember:
- 0 + 0 = 0
- 0 + 1 = 1
- 1 + 0 = 1
- 1 + 1 = 10 (This is equivalent to 2 in decimal, so you write down 0 and carry over 1)
Scenario Example: Imagine counting the number of apple pies sold in two bakeries in New York. The first bakery sold 2 pies, and the second sold 3 pies. In binary, 2 is represented as “10” and 3 as “11”. Adding them:
10 + 11 = 101
This gives us 5 in decimal notation, which is the correct total of pies sold.
Methods to add two binary numbers in Python
There are three different ways in Python to add two binary numbers.
- Built-in bin() function
- Custom Binary Addition Function
- Using Bitwise Operators
Let’s see them one by one with an illustrative example.
Method-1: Using built-in bin() function in Python
Python offers a seamless way to work with binary numbers through its built-in functions. Use the bin() function to convert a decimal to binary in Python. Then, to add them, first convert binary strings to integers. Add the two integers. and Last, Convert the result back to binary.
For instance, In Texas, two tech companies decide to represent their yearly sales in binary through Python. Company A sold products worth $5 (in binary, “101”) and Company B sold products worth $3 (in binary, “11”).
Here’s how we would calculate their total sales using Python’s built-in functions:
company_A = bin(5) company_B = bin(3) total_sales = bin(int(company_A, 2) + int(company_B, 2)) print('Total sales of both company:', total_sales)
The output is:
Total sales of both company: 0b1000
This way we can use the bin() method in Python to add two binaries.
Method-2: Custom Binary Addition Function in Python
Here, we will use different methods to build a function in Python that will add two binary numbers and will return their sum as a binary string.
For instance, In Los Angeles, two film studios decide to represent the number of movies they produced this year in binary Python. Studio A produced 4 movies (“100”) and Studio B produced 2 movies (“10”).
Here’s the custom function in Python to add the two binary numbers:
def binary_addition(studio_A, studio_B): max_len = max(len(studio_A), len(studio_B)) studio_A = studio_A.zfill(max_len) studio_B = studio_B.zfill(max_len) carry = 0 Binary_sum_result = '' for i in range(max_len - 1, -1, -1): bit_sum = carry + int(studio_A[i]) + int(studio_B[i]) Binary_sum_result = str(bit_sum % 2) + Binary_sum_result carry = bit_sum // 2 if carry != 0: Binary_sum_result = str(carry) + Binary_sum_result return Binary_sum_result print(binary_addition("100", "10"))
In this Python code, Make sure both binary numbers are of the same length by adding leading zeros.
First, we find the maximum length between the two binary Python strings. We then use the zfill() Python method to pad the shorter binary string with leading zeros. This ensures that both binary numbers have the same length, which is crucial for the addition process. The carry Python variable is initialized to 0. It is used to store any carry value that might result from adding two bits.
For each bit, we calculate bit_sum by adding the corresponding bits from both strings and any existing carry. bit_sum % 2 gives us the current bit of the result, and bit_sum // 2 provides the carry for the next iteration.
The output is:
The result, “110”, translates to 6 in decimal notation, representing the total movies produced by both studios in Python.
This way we can add two binary no.s in Python.
Method-3: Binary Addition of two numbers using bitwise operators in Python
Python allows direct bitwise operations on integers. Using bitwise operators can be both efficient and intriguing for those interested in a deeper dive.
Scenario Example: In Chicago, two data centers decide to represent the number of servers they have in binary Python. Data Center A has 4 servers (“100”) and Data Center B has 3 servers (“11”).
Here’s how to use bitwise operators in Python to add the two numbers of binary:
def add_using_bitwise(center_a, center_b): while center_b != 0: carry = center_a & center_b center_a = center_a ^ center_b center_b = carry << 1 return bin(center_a) print(add_using_bitwise(0b100, 0b11))
The output is:
The result, “111”, equals 7 in decimal notation, which is the total number of servers in both data centers.
This tutorial explains how to add two binary numbers in Python using 3 different methods like bit() method, function with zfill() method, or function with while loop and operators with demonstrative examples.
You may also like to read:
- Python Code to Print a Binary Tree
- Python Program for Binary Search
- linear search and binary search in Python program
- Add two numbers without using + operator in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.