How to convert binary to decimal in Python
Learn how to convert binary to decimal in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

The conversion of binary to decimal is a frequent task in Python, especially for data work or low-level system interaction. Python's built-in int() function makes this process straightforward.
You'll learn several conversion techniques and get practical tips. You will also explore real-world applications and find advice on how to debug common errors to help you master the process.
Using the int() function with base 2
binary = "1010"
decimal = int(binary, 2)
print(f"Binary {binary} = Decimal {decimal}")--OUTPUT--Binary 1010 = Decimal 10
The int() function is Python's built-in tool for this conversion. The magic lies in its second argument, which specifies the number's base.
- The first argument,
"1010", is the binary number represented as a string. - The second argument,
2, tells Python that the string is in base-2.
This signals the function to perform the conversion from binary to its base-10 decimal equivalent, returning the integer 10. It’s a clean and direct approach that avoids manual calculations.
Basic conversion methods
While int() is the go-to function, you can also work with binary literals using the 0b prefix or dive deeper with manual and bitwise operations.
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
You can define integers directly in binary by using the 0b prefix. When Python sees 0b1010, it interprets the value as an integer from the start, so the variable binary_literal holds the decimal value 10 without needing any conversion function.
- The
0bprefix is a native way to represent binary numbers in your code. - The value is already an integer, not a string that needs parsing.
This approach is especially useful when working with flags or bitmasks where the binary representation is more meaningful.
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
This method mimics the manual math behind binary conversion. It iterates through each digit of the binary string, building the decimal value step by step. The core logic is in the expression decimal = decimal * 2 + int(digit).
- In each loop, the current
decimaltotal is multiplied by2, which is like shifting the value one position to the left. - The integer value of the current digit is then added, updating the total.
This process repeats until all digits are processed, giving you the final decimal equivalent.
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 method is a more performant version of the manual calculation, using bitwise operators for efficiency. The logic hinges on the expression (decimal << 1) | int(bit), which updates the decimal value with each bit from the string.
- The left shift operator
<< 1moves all bits indecimalone position to the left. It’s a fast way to multiply the number by 2. - The bitwise
ORoperator|then sets the rightmost bit by combining the shifted value with the current bit (0or1).
This process efficiently builds the final integer, bit by bit.
Advanced techniques
Beyond the basics, you can also tackle conversions with mathematical functions like sum(), handle raw binary data using int.from_bytes(), or even process fractional numbers.
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 to translate the mathematical definition of binary into code. The sum() function adds up the value of each bit, which is calculated by multiplying the bit by its corresponding power of 2.
reversed(binary)reads the string from right to left, starting with the least significant bit.enumerate()provides the index (idx), which becomes the exponent for the power of 2 calculation, like2 ** idx.- The expression calculates each bit's decimal value, and
sum()totals them for the final result.
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
This method is perfect for handling raw binary data, like information read from a file or a network connection. It works with byte objects, not strings. The code first converts the binary string into an integer and then into a byte object using to_bytes() before int.from_bytes() does the final conversion.
- The
to_bytes()method creates the byte sequence from an integer. int.from_bytes()then converts that byte sequence back into a decimal integer.- The
byteorder='big'argument is crucial—it ensures the bytes are read from most 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
To handle binary numbers with a fractional part, you first split the string at the decimal point using split('.'). The integer portion is converted using the familiar int() function with base 2, while the fractional part requires a different approach.
- A
sum()function calculates the fractional value using negative powers of 2. - Each bit is multiplied by 2 raised to a negative exponent, like
2 ** -(i+1), which corresponds to its position after the decimal point.
The two results are then added together to produce the complete decimal number.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the binary conversion techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a network data visualizer that uses
int.from_bytes()to parse and display packet information in real time. - Create a custom calculator that handles binary numbers with fractional parts, using the logic from the
split('.')method. - Deploy a low-level system utility that interprets hardware flags or permissions represented with the
0bprefix.
Turn your concept into a finished application. Describe your idea to Replit Agent, and it will write, test, and deploy the code for you.
Common errors and challenges
Even with Python's simple tools, you might run into a few common pitfalls during binary to decimal conversions.
Handling leading zeros with the 0b prefix
A common mistake is trying to convert a string that includes the 0b prefix. The int() function expects a string containing only 0s and 1s for base 2, so passing it "0b1010" will raise a ValueError. You'll need to strip the prefix from the string before the conversion can succeed.
Handling invalid characters in binary string conversions
Your binary string must be clean. If it contains any characters besides 0 and 1, such as spaces or other symbols, the int() function will raise a ValueError. It's a good practice to validate or sanitize your strings before conversion, especially when they come from user input or external files.
Removing the 0b prefix when displaying binary numbers
When you convert a number back into binary using the bin() function, Python automatically adds the 0b prefix to the string. While this is useful for code, you might not want it in your output. You can easily get just the digits by slicing the string—for example, bin(10)[2:] returns just "1010".
Handling leading zeros with the 0b prefix
While the 0b prefix is great for defining binary literals, it has a catch. Python immediately interprets the value as an integer, meaning any leading zeros are dropped. This becomes an issue when you need to preserve a specific bit length.
# This doesn't preserve leading zeros
binary = 0b00101
print(f"Binary number: {binary}") # Shows 5, not 00101
The 0b prefix creates an integer, so the binary variable stores 5, and the leading zeros are lost. This becomes an issue when bit length matters. The following code shows how to preserve the original format.
# 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'll want to work with strings. The 0b prefix creates an integer directly, so Python drops any insignificant zeros from the front.
- Store the binary number as a string, like
"00101", to maintain its original format for display or processing. - Use
int("00101", 2)to get its decimal value only when you need to perform calculations.
This approach is crucial when bit length matters, such as in network protocols or hardware interfaces.
Handling invalid characters in binary string conversions
The int() function is strict with base 2 conversions and expects a string containing only '0's and '1's. If your string includes any other character, like a typo or a different digit, Python will raise a ValueError. The code below demonstrates this common error.
user_input = "1012" # Contains non-binary digit '2'
decimal = int(user_input, 2)
print(f"Binary {user_input} = Decimal {decimal}")
The conversion fails because the string "1012" includes the digit '2', which isn't valid in binary. See how you can validate the input first to prevent this error.
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, it's best to validate the string before conversion. This is especially important when handling data from external sources like user input, where formatting isn't guaranteed.
- The expression
all(bit in '01' for bit in user_input)checks that every character is a valid binary digit. - This simple guard ensures your program won't crash from unexpected input, making your code more robust.
Removing the 0b prefix when displaying binary numbers
When converting a decimal to binary with the bin() function, Python automatically adds a 0b prefix to the string. This is standard for code, but you might not want it in your output. The following code demonstrates this default behavior.
decimal_number = 10
binary = bin(decimal_number)
print(f"Decimal {decimal_number} in binary: {binary}")
The code returns "0b1010", a string with a prefix that's not always useful for display. See how to easily remove it in the next example to get just the binary digits you need.
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 slice the output from the bin() function. The expression [2:] is a simple yet powerful trick that tells Python to create a new string starting from the third character.
- This effectively skips the
0bprefix. - It’s a clean way to format binary numbers for display where the prefix isn't needed, ensuring your output is tidy and user-friendly.
Real-world applications
Beyond the mechanics, binary-to-decimal conversion is a practical tool for tasks like interpreting system configuration flags and decoding raw network data.
Reading configuration flags with binary conversion
Many applications use a binary string as a compact way to manage configuration flags, where each bit acts as an on/off switch for a specific feature.
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 snippet shows how to map a binary string to a list of application features. It uses a list comprehension to build a new list, enabled_features, by filtering a predefined list of settings based on the binary input.
- The
enumerate()function iterates over thefeatureslist, providing both an index and the feature name. - An
ifcondition then checks if the character at the corresponding index in theconfig_flagsstring is'1'. - Only features whose flag is
'1'are added to the final list.
Decoding binary protocol data with the int() function
In network programming, the int() function allows you to parse raw binary data from a packet into meaningful segments, such as protocol identifiers or source addresses.
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 long binary string. By specifying start and end indices, you can isolate specific portions of the data.
packet[0:4]grabs the first four characters.packet[4:12]takes the next eight.packet[12:]gets everything from the 12th character to the end.
Each of these smaller strings is then individually converted from binary to a decimal integer using the int() function. This allows you to process different parts of a single data string as separate numerical values.
Get started with Replit
Turn your knowledge into a tool. Tell Replit Agent: "Build a binary-to-decimal calculator that handles fractional numbers" or "Create a network data parser that decodes binary packets into protocol, source, and data values."
Replit Agent writes the code, tests for errors, and deploys your application. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



