Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add binary numbers using Python?
Adding binary numbers in Python can be accomplished by converting binary strings to integers, performing the addition, and converting back to binary format. Python provides built-in functions like int() and bin() to handle these conversions easily.
Converting Binary Strings to Integers
Use int() with base 2 to convert binary strings to decimal integers ?
a = '001'
b = '011'
# Convert binary strings to integers
num_a = int(a, 2)
num_b = int(b, 2)
print(f"Binary {a} = Decimal {num_a}")
print(f"Binary {b} = Decimal {num_b}")
Binary 001 = Decimal 1 Binary 011 = Decimal 3
Adding Binary Numbers
Add the converted integers and use bin() to get the binary result ?
a = '001'
b = '011'
# Convert to integers, add, then convert back to binary
result = int(a, 2) + int(b, 2)
binary_sum = bin(result)
print(f"{a} + {b} = {binary_sum}")
001 + 011 = 0b100
Removing the '0b' Prefix
The bin() function returns a string with '0b' prefix. Use slicing to remove it ?
a = '1011'
b = '1101'
result = int(a, 2) + int(b, 2)
binary_sum = bin(result)[2:] # Remove '0b' prefix
print(f"{a} + {b} = {binary_sum}")
1011 + 1101 = 11000
Complete Function Example
Here's a reusable function to add multiple binary numbers ?
def add_binary(binary1, binary2):
"""Add two binary numbers and return the result as binary string"""
decimal_sum = int(binary1, 2) + int(binary2, 2)
return bin(decimal_sum)[2:]
# Test the function
result1 = add_binary('101', '110')
result2 = add_binary('1111', '1')
print(f"101 + 110 = {result1}")
print(f"1111 + 1 = {result2}")
101 + 110 = 1011 1111 + 1 = 10000
Conclusion
Use int(binary_string, 2) to convert binary to decimal, perform normal addition, then use bin(result)[2:] to get the clean binary result. This method handles binary addition efficiently in Python.
