How to add binary numbers in Python

Key takeaways:

  • Binary numbers are essential to computer systems, aligning with digital hardware states (0 and 1) to enable efficient arithmetic, memory management, and logical operations.

  • Python’s bin() method converts an integer to its binary representation as a string with a 0b prefix.

  • The int() method converts data, including binary strings, to integers by specifying the base. The second parameter in int(binary, 2) specifies that the input is in base-2 (binary format).

  • Binary addition involves converting integers to binary, performing addition, and producing the result in binary.

Binary numbers are the core of the electrical components inside a computer. They simplify the design of computers and related technologies. Python provides simple tools to manipulate and perform operations like addition on binary numbers. This Answer explores how to add binary numbers in Python using built-in functions and manual implementation.

Using Python’s built-in tools

We can add binary numbers using the modules that come pre-built in Python. This involves making use of the following methods. These methods can be used for conversion purposes.

1. The bin() method

One of Python’s built-in functions, bin(), transforms an integer into its binary equivalent. This produces a string as the output, with a prefix added to the converted result to identify it as binary.

Example

Let’s have a look at how we can convert an integer to binary:

integer = 5
num = bin(integer) # convert to binary
print(num)

We want to convert 5 to binary, and when we pass it to the bin() method, we get 0b101. This is a string with a 0b prefix, which indicates that the output string is in binary format, followed by the converted number’s actual binary.

2. The int() method

The int class represents integers in Python. It can store positive and negative integers but cannot hold fractions. The int() method converts a variable of any data type to its corresponding value in the int data type.

Example

Let’s have a look at how we can convert a binary number to an integer:

binary = "101"
num = int(binary, 2) # convert to integer
print(num)

In the code above, we convert our binary number to an integer. Note that the second parameter in line 3 specifies the base of the number system being used for conversion. As binary numbers are in base-2, the 2 tells Python to interpret the string binary as a binary number and convert it into a decimal (base-10) integer.

Adding binary numbers

Now, let’s understand how to add binary numbers:

1. Using built-in functions (bin() and int())

  • Convert binary strings to integers using the int() function.

  • Perform the addition of integers.

  • Convert the result back to binary using bin().

b1='100010' #Decimal value: 34
b2='101001' #Decimal value: 41
res = bin(int(b1,2) + int(b2,2)) #Passing the base value of 2 for binary to the int() function
print(res)
#If the user wants to get rid of the suffix '0b' at the start
print(res[2:])

2. Manual binary addition

  • Manually add the binary numbers bit by bit, handling carryovers like traditional binary addition.

def add_binary_manual(bin1, bin2):
# Make both binary strings equal length
max_len = max(len(bin1), len(bin2))
bin1 = bin1.zfill(max_len)
bin2 = bin2.zfill(max_len)
carry = 0
result = []
for i in range(max_len - 1, -1, -1):
bit1 = int(bin1[i])
bit2 = int(bin2[i])
sum_bits = bit1 + bit2 + carry
if sum_bits == 0:
result.append('0')
carry = 0
elif sum_bits == 1:
result.append('1')
carry = 0
elif sum_bits == 2:
result.append('0')
carry = 1
elif sum_bits == 3:
result.append('1')
carry = 1
if carry:
result.append('1')
# Reverse the result to get the correct order
return ''.join(result[::-1])
# Example usage
bin1 = "1101"
bin2 = "1011"
print(add_binary_manual(bin1, bin2)) # Output: 11000

3. Using the add operator

  • The add operator allows easy manipulation of binary strings, including addition.

from operator import*
num1="1101"
num2="100"
answer = bin(add(int(num1,2),int(num2,2)))
print(answer)

Learn the basics with our engaging “Learn Python” course!

Start your coding journey with Learn Python, the perfect course for beginners! Whether exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun. Join now and start your Python journey today—no prior experience is required!

Conclusion

Understanding binary numbers and their operations is essential for working with computer systems. Python simplifies binary arithmetic through built-in functions like bin() for conversion to binary and int() for conversion to integers. By leveraging these tools, we can efficiently perform binary addition and other operations. This knowledge is crucial for computer architecture, networking, and data encoding, making it a fundamental concept for programmers and engineers.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do you send binary data in Python?

Use Python’s socket module to send binary data by opening a socket and sending data in bytes using the send() or sendall() methods.


How do you find binary in Python?

Use Python’s bin() function to find the binary representation of an integer.


How do you add a binary file in Python?

To add binary files in Python, open them in binary mode ('rb'), read their contents, and process or combine the data as needed.


How do you perform addition in binary numbers?

Binary addition works similarly to decimal addition, but it uses base 2. The rules for adding binary digits (bits) are as follows:

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 = 10 (carry over 1 to the next bit)
Steps for binary addition:
  1. Add the corresponding bits (from right to left).
  2. If the sum is 2 (i.e., 1 + 1), write 0 and carry over 1 to the next column.
  3. If the sum is 1, write 1 with no carry over.
  4. Continue this until you have added all bits.
Example:

Add 1011 and 1101 (binary numbers):

  1011
+ 1101
------
 11000  (Result)
Steps:
  1. 1 + 1 = 10 → Write 0, carry over 1
  2. 1 + 0 + 1 (carry) = 10 → Write 0, carry over 1
  3. 0 + 1 + 1 (carry) = 10 → Write 0, carry over 1
  4. 1 + 1 + 1 (carry) = 11 → Write 1, carry over 1
  5. Write the carry over: 1

Final result: 11000

In Python:

You can also do binary addition using Python’s built-in functions:

bin1 = 0b1011  # Binary number 1011
bin2 = 0b1101  # Binary number 1101

result = bin1 + bin2
print(bin(result))  # Output: 0b11000

In this example, 0b is used to indicate binary numbers in Python.


Free Resources