How to convert a decimal to binary in Python

Learn how to convert decimal to binary in Python. Explore different methods, tips, real-world applications, and common debugging techniques.

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

The conversion of decimal numbers to their binary form is a fundamental skill in programming. Python simplifies this process with built-in functions and straightforward logic for various data applications.

In this article, we'll cover techniques from the bin() function to bitwise operators. We'll also provide real-world applications, practical tips, and advice to help you debug your code.

Using the built-in bin() function

decimal_number = 42
binary_number = bin(decimal_number)
print(f"Decimal {decimal_number} in binary is: {binary_number}")
print(f"Without '0b' prefix: {binary_number[2:]}")--OUTPUT--Decimal 42 in binary is: 0b101010
Without '0b' prefix: 101010

Python’s built-in bin() function is the most direct way to convert an integer to its binary string representation. The function automatically adds a 0b prefix to the output. This prefix is Python's standard notation for a binary literal, which helps distinguish it from other number systems.

In many cases, you'll only need the binary digits themselves, for example, in data serialization or custom formatting. To get a clean binary string, you can use string slicing like [2:] to efficiently remove the prefix, as shown in the example.

Basic conversion methods

Beyond the bin() function, you can gain more control over binary conversions using methods like format(), manual calculations, or even bitwise operations.

Using string formatting with format()

decimal_number = 123
binary_formatted = format(decimal_number, 'b')
binary_padded = format(decimal_number, '08b') # 8-digit padding with zeros
print(f"{decimal_number} → {binary_formatted}")
print(f"{decimal_number} padded → {binary_padded}")--OUTPUT--123 → 1111011
123 padded → 01111011

The format() function offers more flexibility for binary conversions. It produces a clean binary string without the 0b prefix, and its real power lies in formatting options like zero-padding.

  • The format specifier '08b' tells Python to convert the number to binary, ensure it's at least 8 digits wide, and pad with leading 0s if it's shorter.

This is especially useful for aligning data or working with protocols that require fixed-length binary fields.

Manual conversion using division by 2

def decimal_to_binary(n):
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary or "0"

print(decimal_to_binary(25))
print(decimal_to_binary(0))--OUTPUT--11001
0

Implementing the conversion yourself offers a deeper understanding of the underlying logic. This function uses the classic division-by-2 method inside a while loop, which runs until the number is zero.

  • The modulo operator (n % 2) calculates the remainder, giving you the rightmost binary digit.
  • This digit is added to the front of the result string using techniques similar to converting integers to strings.
  • Integer division (n //= 2) prepares the number for the next iteration.

The final or "0" is a concise way to handle the edge case where the input is 0.

Converting with bitwise operations

def bitwise_decimal_to_binary(n):
if n == 0:
return "0"
binary = ""
while n:
binary = str(n & 1) + binary
n >>= 1
return binary

print(bitwise_decimal_to_binary(15))
print(bitwise_decimal_to_binary(170))--OUTPUT--1111
10101010

Bitwise operations provide a highly efficient, low-level way to handle binary conversions. This method is often faster than standard arithmetic because it manipulates the data at the bit level, similar to techniques used when converting binary to integer. The function iterates as long as the number isn't zero, processing one bit in each loop.

  • The bitwise AND, n & 1, isolates the rightmost bit (either 1 or 0).
  • The right shift, n >>= 1, moves every bit one position to the right, preparing the next bit for the next iteration.

Advanced binary conversion techniques

Building on these foundational methods, you can also tackle binary conversions with more structured approaches like recursion, list manipulation, and even object-oriented design.

Recursive decimal to binary conversion

def recursive_to_binary(n):
if n == 0:
return "0"
elif n == 1:
return "1"
else:
return recursive_to_binary(n // 2) + str(n % 2)

print(recursive_to_binary(10))
print(recursive_to_binary(255))--OUTPUT--1010
11111111

Recursion offers an elegant way to approach this conversion. The recursive_to_binary function breaks the problem down by repeatedly calling itself with a smaller value until it reaches a simple base case.

  • The function stops when the number is 0 or 1, returning the corresponding string.
  • For any other number, it calls itself with n // 2 and appends the current remainder (n % 2) to the result.

This process builds the binary string from left to right as the function calls resolve, starting from the deepest call and working back up.

Working with binary numbers in lists

decimal_numbers = [5, 10, 15, 20]
binary_numbers = [bin(num)[2:] for num in decimal_numbers]
binary_dict = {num: bin(num)[2:] for num in decimal_numbers}

print(binary_numbers)
print(binary_dict)--OUTPUT--['101', '1010', '1111', '10100']
{5: '101', 10: '1010', 15: '1111', 20: '10100'}

Python’s comprehensions are perfect for converting multiple numbers at once. The example uses a list comprehension to iterate through decimal_numbers, applying bin(num)[2:] to each one and collecting the results into a new list.

  • List comprehension: Creates a new list, binary_numbers, containing only the binary strings.
  • Dictionary comprehension: Builds a dictionary, binary_dict, that maps each original decimal number to its binary equivalent, which is useful for lookups.

This approach is concise and highly readable, making it a go-to for batch data processing.

Creating a BinaryNumber class

class BinaryNumber:
def __init__(self, decimal_value):
self.decimal = decimal_value
self.binary = bin(decimal_value)[2:]

def __str__(self):
return f"{self.decimal} (decimal) = {self.binary} (binary)"

print(BinaryNumber(42))
print(BinaryNumber(255))--OUTPUT--42 (decimal) = 101010 (binary)
255 (decimal) = 11111111 (binary)

An object-oriented approach lets you package data and functionality together. This BinaryNumber class encapsulates the conversion logic, making your code more organized and reusable. For more details on the fundamentals of creating classes in Python, you can explore class design principles. When you create an instance, its behavior is defined by two key methods:

  • The __init__ constructor runs automatically, storing both the original decimal and its converted binary string.
  • The __str__ method provides a clean, readable output when you print() the object, which is far more useful than a default memory address.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly.

Instead of piecing together techniques, you can use Agent 4 to build complete applications from a simple description. For example, you could build:

  • A network protocol tool that converts decimal values into padded binary strings for packet analysis.
  • A file permission calculator that translates numeric codes into their binary form to visualize user rights.
  • A data serialization utility that transforms a list of integers into a compact binary string for efficient storage.

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

Common errors and challenges

Even with Python's simple tools, you might run into a few common pitfalls when converting decimals to binary.

  • Dealing with TypeError. The bin() function only accepts integers. If you pass it a string, even one containing a number like "42", Python will raise a TypeError. Always convert string inputs to integers with int() first.
  • Handling negative numbers. While bin() handles negative numbers automatically, custom conversion functions often don't. A loop based on division will fail, so a better approach is to convert the number's absolute value and then manually add a negative sign to the result.
  • Adding binary strings. Using the + operator on binary strings concatenates them (e.g., "101" + "10" becomes "10110") instead of performing arithmetic. To add them correctly, convert each string to an integer using int(your_string, 2), sum them, and then convert the result back to binary.

Dealing with TypeError when using bin() with strings

A common mistake is passing a string to the bin() function, which only accepts integers. This action raises a TypeError because Python won't automatically convert the string for you. The following code demonstrates what happens when you try this.

user_input = "42"
binary_result = bin(user_input)
print(f"Binary representation: {binary_result}")

The code fails because the user_input variable holds a string, not a number. The bin() function isn't designed to interpret the characters in a string. Check the corrected code below to see how to resolve this.

user_input = "42"
binary_result = bin(int(user_input))
print(f"Binary representation: {binary_result}")

The fix is to explicitly convert the string to an integer using the int() function. By wrapping user_input in int(), you're telling Python to parse the string and return its numerical value. The bin() function can then correctly process the integer. This error is especially common when handling data from user input or reading from files, as that data often arrives as strings.

Handling negative numbers in custom binary conversion

While Python’s built-in bin() function handles negative numbers, custom conversion functions often break. A common method using a while n > 0 loop and division won't work for negative inputs because the loop condition is never met, leading to incorrect output. The code below shows what happens when you pass a negative number to a function that isn't built to handle it.

def convert_to_binary(n):
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary or "0"

print(convert_to_binary(-10)) # Infinite loop or incorrect result

The while n > 0 loop never executes for negative numbers, causing the function to immediately return an empty string. The corrected code below shows how to properly handle these cases.

def convert_to_binary(n):
if n < 0:
return "-" + convert_to_binary(abs(n))
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary or "0"

print(convert_to_binary(-10))

The fix is to handle the negative sign separately. The function first checks if the number is negative with an if n < 0: condition. If true, it prepends a "-" sign to the result and then calls itself recursively with the number’s absolute value, found using abs(n). This lets the core conversion logic work on a positive number, neatly sidestepping the infinite loop problem. It’s a simple, effective pattern for custom conversion functions.

Adding binary strings correctly with int() and base conversion

Adding binary strings correctly with int() and base conversion

A frequent mistake is using the + operator to add binary strings, which only joins them together. This is string concatenation, not mathematical addition. To get the correct sum, you must first convert the strings to integers. The code below shows what happens.

binary_a = "1010" # 10 in decimal
binary_b = "1100" # 12 in decimal
result = binary_a + binary_b
print(f"Sum of {binary_a} and {binary_b} is: {result}")

The code incorrectly produces "10101100" because the + operator treats the variables as text and joins them. It doesn't perform a mathematical calculation. The corrected code below demonstrates the right way to add them.

binary_a = "1010" # 10 in decimal
binary_b = "1100" # 12 in decimal
result = bin(int(binary_a, 2) + int(binary_b, 2))[2:]
print(f"Sum of {binary_a} and {binary_b} is: {result}")

The solution involves converting each binary string to an integer before you perform any math. The int() function is perfect for this—just pass 2 as the second argument to tell it you're working with a base-2 number. Once they're integers, you can add them normally. Finally, use bin() to convert the result back into a binary string. This process is the reverse of converting binary to decimal, and it's a crucial step when handling binary data from files or user input.

Real-world applications

These conversion techniques are more than just theory—they’re essential for practical tasks like managing permissions and decoding digital color data.

Implementing binary flags with the | and & operators

Binary flags offer a memory-efficient way to manage multiple on/off states, like user permissions or feature toggles, using bitwise operators like | and &.

# Define features as binary flags
FEATURE_A = 0b0001 # 1 in decimal
FEATURE_B = 0b0010 # 2 in decimal
FEATURE_C = 0b0100 # 4 in decimal

# User with features A and C enabled
user_settings = FEATURE_A | FEATURE_C
print(f"User settings in binary: {bin(user_settings)}")
print(f"Feature A enabled? {bool(user_settings & FEATURE_A)}")
print(f"Feature B enabled? {bool(user_settings & FEATURE_B)}")

This code shows how to manage multiple settings within a single number using bitwise operations. Each FEATURE variable is assigned a unique power of two, representing a single on/off switch.

  • The bitwise OR operator (|) combines FEATURE_A and FEATURE_C into the user_settings variable, effectively flipping both switches on.
  • To check if a specific feature is enabled, you use the bitwise AND operator (&). If the result of user_settings & FEATURE_A is not zero, it confirms the feature is active.

Decoding RGB colors using the >> and & operators

Bitwise operations like right shift (>>) and AND (&) are also essential for unpacking individual color channels from a single integer, a common task in graphics programming.

# RGB color as a single integer (0xRRGGBB format)
color = 0x1A8F37 # A green color in hexadecimal

# Extract RGB components using binary operations
red = (color >> 16) & 0xFF
green = (color >> 8) & 0xFF
blue = color & 0xFF

print(f"Color: {hex(color)}")
print(f"RGB: ({red}, {green}, {blue})")
print(f"Binary - R: {bin(red)}, G: {bin(green)}, B: {bin(blue)}")

This code unpacks a single integer into its red, green, and blue components. Since each color channel is represented by 8 bits, bitwise operations are a natural fit for isolating them.

  • The right shift operator, >>, moves the bits for a specific color into the rightmost position. For example, color >> 16 prepares the red value.
  • The bitwise AND operator, & 0xFF, then acts as a mask to isolate those 8 bits, giving you the final value for that channel.

Get started with Replit

Now, turn your knowledge into a working tool with Replit Agent. Describe what you want to build, like “a network utility that converts decimal inputs to padded binary strings” or “a permission calculator using bitwise operators.”

Replit Agent will write the code, test for errors, and deploy your application for you. 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.