How to convert binary to decimal in Python

Discover multiple ways to convert binary to decimal in Python. Get tips, see real-world uses, and learn how to debug common errors.

How to convert binary to decimal in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Binary to decimal conversion is a frequent programming task, especially for low-level data operations. Python provides straightforward, built-in functions that make this process simple with clean and efficient syntax.

In this article, you'll explore several conversion techniques, from the built-in int() function to custom logic. You'll also find practical tips, real-world applications, and debugging advice to help you confidently handle binary data.

Using the int() function with base 2

binary = "1010"
decimal = int(binary, 2)
print(f"Binary {binary} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10

Python's built-in int() function offers the most direct way to handle this conversion. The key is its second parameter, which specifies the number's base. When you provide 2 as the argument, you instruct the function to treat the input string as a binary value. For more details on using the int() function, you can explore its various applications.

This method requires the binary number to be a string, such as "1010". The function then correctly parses it according to base-2 rules and returns its decimal equivalent. It's an efficient and highly readable solution for converting binary to integer that avoids the need for manual calculation logic.

Basic conversion methods

Beyond the int() function, Python offers more fundamental approaches, from using the 0b prefix for binary literals to building the conversion logic yourself.

Using the 0b prefix for binary literals

binary_literal = 0b1010
decimal = binary_literal
print(f"Binary literal 0b1010 = Decimal {decimal}")--OUTPUT--Binary literal 0b1010 = Decimal 10

Python lets you define binary numbers directly in your code using the 0b prefix. When the interpreter sees 0b, it reads the following digits as a base-2 number. This is different from passing a string to the int() function.

  • The expression 0b1010 is a binary literal that Python immediately evaluates to the integer 10.
  • The variable binary_literal doesn't store a binary string; it holds the resulting decimal value directly.

This approach is handy for hardcoding binary values like configuration flags or bitmasks.

Manual conversion with digit-by-digit calculation

binary = "1010"
decimal = 0
for digit in binary:
decimal = decimal * 2 + int(digit)
print(f"Binary {binary} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10

You can also convert a binary string by processing it digit by digit. This loop iterates through each character in the string, updating the decimal total with each pass. The core logic, decimal = decimal * 2 + int(digit), cleverly mimics how base-2 numbers work.

  • Multiplying the running total by 2 effectively shifts its value one position to the left.
  • Adding the next int(digit) incorporates the new bit into the total at its correct place value.

Using bit shifting and bitwise OR operations

binary = "1010"
decimal = 0
for bit in binary:
decimal = (decimal << 1) | int(bit)
print(f"Binary {binary} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10

This approach is a more performant version of the manual loop, using bitwise operations for efficiency. The logic inside the loop, (decimal << 1) | int(bit), directly manipulates the bits of the number.

  • The left shift operator << 1 moves all bits in decimal one position to the left, effectively multiplying its value by two.
  • The bitwise OR operator | then combines this shifted result with the new bit, setting the least significant bit.

This method achieves the same outcome with operations that are often faster at the hardware level.

Advanced techniques

Building on the fundamental methods, you can also leverage functional programming with sum(), manage byte-level data with int.from_bytes(), and even parse fractional binary values.

Converting with the sum() function and powers of 2

binary = "1010"
decimal = sum(int(digit) * (2 ** idx) for idx, digit in enumerate(reversed(binary)))
print(f"Binary {binary} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10

This one-liner uses a generator expression with the sum() function to perform the conversion. It's a functional approach that directly applies the mathematical formula for binary numbers by calculating the value of each bit's position and adding them together.

  • The reversed() function iterates through the binary string from right to left, which is essential for correct place value calculation.
  • When using enumerate(), it provides an index (idx) for each digit, corresponding to its power of two.
  • Each digit is multiplied by 2 raised to its index (2 ** idx), and sum() adds up the results.

Using the int.from_bytes() method for binary data

binary_string = "1010"
binary_bytes = int(binary_string, 2).to_bytes((len(binary_string) + 7) // 8, byteorder='big')
decimal = int.from_bytes(binary_bytes, byteorder='big')
print(f"Binary {binary_string} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10

The int.from_bytes() method is designed for converting raw binary data, such as bytes from a file or network stream, into an integer. It’s less for direct string conversion and more for handling byte-level information.

  • The code first converts the integer representation of the binary string into a bytes object using to_bytes().
  • Then, int.from_bytes() reads this bytes object to produce the final integer.
  • The byteorder='big' argument is crucial, as it tells Python to interpret the bytes from most significant to least significant.

Converting binary numbers with fractional parts

binary = "1010.101"
integer_part, fractional_part = binary.split('.')
decimal_integer = int(integer_part, 2)
decimal_fraction = sum(int(bit) * (2 ** -(i+1)) for i, bit in enumerate(fractional_part))
print(f"Binary {binary} = Decimal {decimal_integer + decimal_fraction}")--OUTPUT--Binary 1010.101 = Decimal 10.625

This method handles binary numbers with a fractional component by splitting the string at the decimal point using split('.'). While the integer part is converted normally with int(), the fractional part requires a different approach using negative powers of two that could be explored through vibe coding.

  • A sum() expression iterates through each digit after the point.
  • Each digit's value is calculated by multiplying it by 2 raised to a negative exponent, like 2**-1, 2**-2, and so on.

Finally, the resulting integer and fractional values are added together for the complete decimal number.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies are pre-installed, so you can skip setup and start coding instantly. It’s designed to help you go from learning individual techniques to building complete applications faster.

With Agent 4, you can move beyond piecing together functions and build a complete app from a description. For example, you could build:

  • A binary-to-decimal converter utility that handles both integer and fractional inputs, like 1010.101.
  • A network packet analyzer that reads byte streams and converts specific segments into decimal integers for a dashboard.
  • A configuration flag parser that takes a binary string and translates it into a set of active or inactive feature settings for an application.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While Python's tools are powerful, you might encounter a few common pitfalls when converting binary numbers, especially with formatting and invalid data.

A frequent point of confusion involves the 0b prefix. This prefix is for defining a binary literal directly in your code (e.g., my_num = 0b1010), not for use in a string passed to the int() function. Attempting to run int('0b1010', 2) will raise a ValueError because the function doesn't recognize b as a valid binary digit. Always ensure your string contains only the binary digits; if a prefix is present, you must remove it before conversion.

Similarly, the int() function is strict about its input when converting from base 2. The string must contain only '0' and '1' characters. Any stray character, including spaces or other digits, will trigger a ValueError. To create more resilient code, it's a good practice to wrap your conversion logic in a try-except block. This lets you catch and manage invalid inputs gracefully with using try-except blocks instead of having the error halt your program.

When converting in the other direction—from decimal to binary—the built-in bin() function returns a string that includes the 0b prefix. For example, bin(10) evaluates to '0b1010'. If you only need the digits for display or further processing, you can easily remove the prefix. A common method is string slicing (bin(10)[2:]), or you can use the format() function, like format(10, 'b'), to get a clean string without the prefix.

Handling leading zeros with the 0b prefix

While the 0b prefix is convenient, it's important to remember that it creates an integer, not a string. This means any leading zeros in your binary literal are dropped because the resulting integer value doesn't preserve them. The code below demonstrates this.

# This doesn't preserve leading zeros
binary = 0b00101
print(f"Binary number: {binary}") # Shows 5, not 00101

The 0b prefix tells Python to read 0b00101 as a number, not a string. Since leading zeros don't change an integer's value, they're discarded during evaluation. The following code shows how to handle this.

# Use string for displaying with leading zeros
binary_str = "00101"
binary_val = int(binary_str, 2)
print(f"Binary number: {binary_str}, Value: {binary_val}")

To preserve leading zeros, you must work with strings. The code demonstrates this by storing the binary number as a string, like "00101", which maintains its original format for display. You can then use int() to get its numerical value for calculations. This is crucial when the exact bit representation matters—such as with fixed-width data or hardware interfaces where every bit, including leading zeros, is significant.

Handling invalid characters in binary string conversions

Your binary strings must be clean—containing only '0's and '1's—for the int() function to work. If an invalid character slips in, Python will raise a ValueError. The code below shows what happens with an input like "1012".

user_input = "1012" # Contains non-binary digit '2'
decimal = int(user_input, 2)
print(f"Binary {user_input} = Decimal {decimal}")

The int() function expects only '0' and '1' for base 2, so the character '2' in "1012" causes a ValueError. The code below shows how you can catch this error and prevent your program from crashing.

user_input = "1012" # Contains non-binary digit '2'
if all(bit in '01' for bit in user_input):
decimal = int(user_input, 2)
print(f"Binary {user_input} = Decimal {decimal}")
else:
print(f"Error: '{user_input}' contains non-binary digits")

To prevent a ValueError, you can validate the string before conversion. The expression all(bit in '01' for bit in user_input) checks if every character is a valid binary digit. This is a clean way to handle potentially malformed data from user input or external files without needing a try-except block. This approach lets you provide a clear error message if the check fails, preventing the program from crashing with automated code repair.

Removing the 0b prefix when displaying binary numbers

When converting decimal to binary using the bin() function, Python automatically adds a 0b prefix to the resulting string. This can be inconvenient for display or further processing. The code below shows how bin(10) returns '0b1010'.

decimal_number = 10
binary = bin(decimal_number)
print(f"Decimal {decimal_number} in binary: {binary}")

The bin() function's output includes the 0b prefix, which you often need to remove for clean formatting or subsequent processing. The following code demonstrates how to get just the binary digits.

decimal_number = 10
binary = bin(decimal_number)[2:] # Remove '0b' prefix
print(f"Decimal {decimal_number} in binary: {binary}")

To get a clean binary string, you can use Python's string slicing. The expression bin(decimal_number)[2:] takes the output, like '0b1010', and creates a new string starting from index 2. This neatly strips the leading '0b' prefix. It’s a simple and effective trick for when you need the pure binary digits for display or further processing, ensuring your output is formatted exactly as you need it.

Real-world applications

Beyond the syntax, these conversion techniques are fundamental for practical tasks like interpreting configuration flags and decoding binary data protocols.

Reading configuration flags with binary conversion

In many applications, a binary string serves as a compact set of configuration flags, allowing you to enable or disable features by checking the value of each bit.

config_flags = "10110" # Binary representation of feature flags
features = ["dark_mode", "notifications", "auto_save", "analytics", "high_contrast"]
enabled_features = [feature for i, feature in enumerate(features) if config_flags[i] == "1"]
print(f"Binary configuration: {config_flags}")
print(f"Enabled features: {enabled_features}")

This code demonstrates how a binary string can act as a switchboard for application features. The config_flags string and the features list are linked by their positions. A list comprehension efficiently filters the features.

  • It pairs each feature with its corresponding bit in config_flags using enumerate().
  • If a bit is '1', the corresponding feature is considered "on" and added to the enabled_features list.

This creates a dynamic way to manage settings from a single, compact string.

Decoding binary protocol data with the int() function

In networking and file parsing, the int() function is crucial for decoding binary data streams where specific segments of a string represent different pieces of information.

packet = "10001011000010101111"
# Extract components (first 4 bits = protocol, next 8 = source, rest = data)
protocol = int(packet[0:4], 2)
source = int(packet[4:12], 2)
data = int(packet[12:], 2)
print(f"Packet: {packet}")
print(f"Protocol: {protocol}, Source: {source}, Data value: {data}")

This code uses string slicing to carve up a single binary string, packet, into meaningful chunks. Each chunk represents a different value, and you can convert them individually into decimal numbers using int() with a base of 2.

  • The slice packet[0:4] isolates the first four bits.
  • packet[4:12] pulls out the next eight bits.
  • packet[12:] captures everything that remains.

It’s a powerful pattern for unpacking data from compact binary formats without needing complex parsing libraries.

Get started with Replit

Put your knowledge into practice by building a real tool. Give Replit Agent a prompt like "build a binary converter that handles fractional inputs" or "create a utility to decode binary configuration flags."

It will write the code, test for errors, and deploy your app. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.