How to Convert Binary String to Int in Python?

As a Python developer, working on various projects involving IoT devices and network communications, I have often come across situations where data arrives in binary form and need to be converted to int. In this article, I will explain how to convert binary string to int in Python with examples and screenshots.

Convert Binary String to Int in Python

Let me explain important methods to convert binary string to int in Python.

Read How to Get the Length of a String in Python?

Method 1: Use Python’s Built-in int() Function

The simplest and most efficient way to convert a binary string to an integer in Python is using the built-in function int(). This function accepts two parameters: the string to convert and the base of the number system.

# Converting a binary string to integer
binary_string = "11111111"
decimal_value = int(binary_string, 2)
print(decimal_value)

Output:

255

I executed the above example code and added the screenshot below.

Convert Binary String to Int in Python

The second parameter (base=2) tells Python that the input string should be interpreted as a binary number. This method is clean, efficient, and part of Python’s standard library.

Handle Binary Strings with ‘0b’ Prefix

Sometimes binary strings come with the ‘0b’ prefix. The int() function can handle this too:

# Binary string with '0b' prefix
binary_with_prefix = "0b1010"
decimal_value = int(binary_with_prefix, 2)
print(decimal_value)  # Output: 10

Wait, that won’t work! When using the base parameter with int(), you should not include the ‘0b’ prefix. Let me correct this:

# Binary string with '0b' prefix - two approaches
binary_with_prefix = "0b1010"

# Method 1: Strip the prefix and use base=2
decimal_value = int(binary_with_prefix[2:], 2)

# Method 2: Let Python interpret it directly
decimal_value = int(binary_with_prefix, 0)

print(decimal_value)  # Output: 10

Check out How to Check if a String is Empty in Python?

Method 2: Use the bitstring Library

When working with more complex binary data like embedded systems, network protocols, or custom binary file formats—the built-in methods of Python might not be enough. That’s where the bitstring library becomes incredibly useful.

# First, install the library
# pip install bitstring

from bitstring import BitArray

# Convert binary string to int
binary_string = "10101010"
bit_array = BitArray(bin=binary_string)
decimal_value = bit_array.uint  # For unsigned integers
print(decimal_value)

Output:

170

I executed the above example code and added the screenshot below.

How to Convert Binary String to Int in PythonHow to Convert Binary String to Int in Python

The bitstring library goes beyond what built-in Python functions can do by giving you more control and readability when working with binary data.

Read Convert DateTime to UNIX Timestamp in Python

Method 3: Manual Conversion (Educational Purpose)

While Python provides built-in ways and libraries to convert binary strings to integers, manually implementing this logic is a great educational exercise.

def binary_to_int_manual(binary_string):
    decimal_value = 0
    for digit in binary_string:
        decimal_value = decimal_value * 2 + int(digit)
    return decimal_value

# Test our function
binary_string = "1101"
print(binary_to_int_manual(binary_string))

Output:

13

I executed the above example code and added the screenshot below.

Convert Binary String to Int in Python manual conversion

This method follows the mathematical principle of base-2 number conversion, where each digit’s position represents a power of 2.

Check out Concatenate String and Float in Python

Handle Different Binary String Formats while performing conversion

I will explain how to handle different binary formats that you may encounter while converting binary strings to int.

Convert Large Binary Strings

When working with very large binary numbers, you might worry about performance or memory limitations. Fortunately, Python is extremely well-suited for this kind of task, thanks to its built-in support for arbitrary-precision integers.

# Large binary number
large_binary = "1" * 100  # 100 ones
large_decimal = int(large_binary, 2)
print(large_decimal)  # A very large number!
print(f"Number of digits: {len(str(large_decimal))}")

Convert Binary Strings with Spaces or Separators

In real-world projects dealing with data from hardware, networking logs, or communication protocols—you may encounter binary strings that include spaces, commas, or other separators to improve readability.

# Binary with spaces
spaced_binary = "1010 1010 1111 0000"
clean_binary = spaced_binary.replace(" ", "")
decimal_value = int(clean_binary, 2)
print(decimal_value)  # Output: 44240

Read How to Find the Largest and Smallest Numbers in Python?

Performance Comparison

Let me show you the comparison of all the methods that we discussed to convert binary strings to int.

MethodProsConsBest For
int() functionFast, built-in, simpleLimited to standard conversionMost everyday use cases
bitstring libraryVersatile, handles complex binary operationsExternal dependencyComplex binary manipulations
Manual conversionEducational, customizableSlower, more codeLearning and specialized needs

Common Errors and Solutions

Let me explain to you some common errors that you might face while converting binary strings and solution for it.

Check out How to Check if a Python String Contains a Substring?

ValueError: Invalid Literal for int() with Base 2

This error occurs when your binary string contains characters other than 0 and 1:

try:
    int("10102", 2)  # Will raise ValueError (contains '2')
except ValueError as e:
    print(f"Error: {e}")

Solution: Always validate your binary string before conversion:

def is_valid_binary(s):
    return all(bit in '01' for bit in s)

binary_string = "10102"
if is_valid_binary(binary_string):
    decimal_value = int(binary_string, 2)
else:
    print("Invalid binary string")

Overflow Errors

Python handles integers with arbitrary precision, so you won’t encounter overflow errors with standard integers. However, when working with fixed-width integer types (like in NumPy), be cautious of potential overflow.

Read How to Reverse a String in Python?

Practical Applications

Let us understand more about the conversion of binary strings to int in Python by considering some practical applications.

Read Binary Configuration Files

In the example below, we break down a binary configuration string into separate fields using slicing and convert each part to integers for easy interpretation.

def parse_binary_config(config_string):
    settings = {}
    # First 8 bits represent version
    settings['version'] = int(config_string[:8], 2)
    # Next 4 bits represent mode
    settings['mode'] = int(config_string[8:12], 2)
    # And so on...
    return settings

config = "0101010100110110"
print(parse_binary_config(config))

Binary Data Manipulation in Network Protocols

The example below shows how to parse a simple 8-bit packet header into distinct fields like packet_type, priority, and has_payload.

def extract_header_fields(binary_header):
    fields = {
        'packet_type': int(binary_header[:4], 2),
        'priority': int(binary_header[4:7], 2),
        'has_payload': int(binary_header[7:8], 2) == 1
    }
    return fields

packet_header = "10110101"
print(extract_header_fields(packet_header))

Check out Find the First Number in a String in Python

Conclusion

In this tutorial, I will explain how to convert binary string to int in Python. I discussed methods such as using Python’s built-in int() function, using the bitstring library and manual conversion. I also covered how to handle different binary formats, performance comparisons, and practical applications.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.