October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Python Program to Add Two Binary Numbers

Use Python's int(value, 2) to parse binary strings, add them, and format the result with format(total, "b").

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert each binary string to a Python integer with base 2, add the values, then format the sum in base 2. The program below accepts non-empty strings made only of 0 and 1, allows leading zeros, and prints the result without a 0b prefix.

Python program using integer conversion

This version is concise and practical when the goal is to add two binary values, rather than to implement binary arithmetic digit by digit.

As an Amazon Associate I earn from qualifying purchases.

def add_binary(a: str, b: str) -> str:
    if not a or not b or any(bit not in "01" for bit in a + b):
        raise ValueError("Inputs must be non-empty binary strings")
    return format(int(a, 2) + int(b, 2), "b")

first = input("Enter the first binary number: ").strip()
second = input("Enter the second binary number: ").strip()

try:
    print("Sum:", add_binary(first, second))
except ValueError as error:
    print(error)

For example, entering 1011 and 1101 prints Sum: 11000. Those inputs represent decimal 11 and 13, whose sum is decimal 24, or binary 11000.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the conversion works

  1. int(a, 2) interprets the text in a as a base-2 integer. For example, int("1011", 2) is 11. See the Python documentation for int.
  2. The + operator adds the resulting integer values.
  3. format(total, "b") converts the sum to binary digits. The Python documentation defines bin(x) as converting an integer to a binary string prefixed with 0b; using format(total, "b") avoids that prefix for this non-negative result. See Python’s bin documentation.

Input behavior and validation

  • Accepted: one or more characters, all of which must be 0 or 1.
  • Leading zeros: accepted. For example, 001 and 1 are both interpreted as the value one; the output is the normalized binary sum, without unnecessary leading zeros.
  • Empty input or other characters: rejected with a ValueError message instead of being silently changed.
  • Signs: not accepted by this function, because its stated input format is binary digits only.

The input calls use .strip() to remove surrounding whitespace before validation. Avoid parsing untrusted numeric text with eval: it executes the supplied code rather than simply parsing a number, as noted by the Python Wiki’s discussion of eval.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use a manual carry algorithm instead

Integer conversion is the appropriate choice for a short utility. If an exercise specifically asks you to implement binary addition, use a right-to-left digit algorithm: add corresponding bits and a carry, write the result bit, and carry any remaining value into the next column. That approach makes the arithmetic visible; conversion through int and format delegates it to Python’s built-ins.

Python integers are not restricted to a fixed machine-word range: their practical size is limited by available memory, according to the Python documentation on numeric types. A direct digit algorithm can avoid constructing large integer objects for extremely long input strings, but this does not establish that it will be faster for a particular workload.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.