October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober 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

How to Convert a Binary String to an Integer in Python

Use Python’s int(binary_text, 2) to parse a binary string. This guide explains prefixes, valid input, ValueError handling, fixed-width bit patterns, and converting back to binary text.

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.

Pass the binary string to Python’s built-in int() function with base 2: int("1010", 2) returns 10. The explicit base matters because an unprefixed string is otherwise read as decimal.

Convert a binary string to an integer

Use int(text, 2), where text contains the binary digits:

value = int("1010", 2)
print(value)  # 10

The second argument is the radix, or base. Python’s documentation describes a base-n integer string as containing digits whose values run from 0 to n−1. For base 2, the allowed digits are therefore 0 and 1. The Python built-in functions reference documents this behavior, including int('01110011', base=2) == 115.

Choose the base explicitly or infer it from a prefix

For an unprefixed string such as "1010", specify base 2. Without that argument, int() uses decimal interpretation, so the string would represent one thousand and ten rather than ten.

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

A base-2 call also accepts an optional 0b or 0B prefix: int("0b1010", 2) returns 10. Use base 0 only when a recognized prefix should determine the base. For example, int("0b1010", 0) infers binary, while a plain string such as "1010" has no prefix to identify its intended base. Base zero also rejects some leading-zero forms, including "010". See the built-in int() reference for the parsing rules.

Input forms and invalid strings

Python permits a leading plus or minus sign, surrounding whitespace, leading zeros, and single underscores between digits. For example, int(" -001_010 ", 2) returns -10. Malformed underscore placement or characters other than binary digits (apart from the permitted sign, whitespace, separators, and optional prefix) make conversion fail with ValueError.

If input may be invalid, handle that expected failure explicitly:

def parse_binary(text):
    try:
        return int(text, 2)
    except ValueError:
        return None  # Replace with the application's error handling

Returning None is only an example; choose a response that fits the program, such as reporting an invalid value or asking for corrected input.

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

Integer parsing does not preserve bit width

The result is a Python integer value, not a fixed-width bit field. Leading zeros disappear as a representational detail: int("00001010", 2) is simply 10. If the string encodes a fixed-width value—especially a signed two’s-complement pattern—decoding requires its specified width and signedness. The ordinary int(text, 2) conversion does not infer either property.

Format the integer as binary again

Use bin(value) for binary text with a 0b prefix. Use format(value, "b") when you want digits without that prefix:

value = int("1010", 2)
print(bin(value))          # 0b1010
print(format(value, "b"))  # 1010

For a negative integer, bin() places the minus sign before the prefix.

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

Do not use eval() for conversion

eval() executes Python expressions rather than parsing a binary numeral. Python’s programming FAQ warns that it is slower and creates a security risk. Use int(text, 2) for this task.

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

Very large binary strings and Python versions

Python documents limits on integer string conversions in some cases. In the Python 3.12 built-in types documentation, conversion between strings and integers in base 2 is exempt from the integer-string conversion limit, as are other power-of-two bases. Because this behavior is version-specific, check the documentation for the Python version you deploy if your program handles exceptionally large values. See the Python 3.12 integer string conversion length limitation notes.

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.

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.