How to convert a number to binary in Python

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

How to convert a number to binary in Python
Published on: 
Tue
Mar 3, 2026
Updated on: 
Wed
Apr 1, 2026
The Replit Team

In Python, number to binary conversion is a fundamental programming task. The language offers straightforward built-in functions, such as bin(), to handle this operation for data manipulation and low-level work.

In this guide, you'll explore multiple conversion techniques beyond the basic bin() function. You will also find practical implementation tips, review real-world applications, and get advice to help you debug common issues.

Using the built-in bin() function

num = 42
binary = bin(num)
print(f"The binary representation of {num} is: {binary}")--OUTPUT--The binary representation of 42 is: 0b101010

The bin() function is Python's most direct tool for this conversion. It takes an integer, like 42, and returns its binary equivalent as a string.

Notice the output 0b101010. The 0b prefix is Python's way of signaling that the following digits represent a binary number. This is useful for clarity and consistency within the language. If your application requires just the binary digits, you can easily strip this prefix using string slicing, for example, binary[2:].

Working with binary strings

Once you have a binary string, you'll often need to clean it up, format it for specific outputs, or even convert it back into an integer.

Removing the 0b prefix from binary representation

num = 42
binary = bin(num)[2:] # Slicing to remove '0b' prefix
print(f"Binary without prefix: {binary}")--OUTPUT--Binary without prefix: 101010

Since bin() returns a string, you can use Python's slicing feature to trim the prefix. The [2:] notation is a concise way to get a substring starting from the third character—at index 2—all the way to the end.

This approach is useful when you need the raw binary value for further processing or display. It works because:

  • The string starts with 0 at index 0 and b at index 1.
  • The slice [2:] begins right after the prefix, capturing only the binary digits.

Formatting binary numbers with format()

num = 42
binary = format(num, 'b')
binary_with_padding = format(num, '08b') # 8-digit padded binary
print(f"Simple binary: {binary}")
print(f"Padded binary: {binary_with_padding}")--OUTPUT--Simple binary: 101010
Padded binary: 00101010

The format() function offers a more flexible way to handle binary conversions. Using format(num, 'b') gives you the binary string directly, without the 0b prefix you get from bin(). This can save you a step if you don't need the prefix.

  • The real power of format() comes from its formatting options.
  • For example, format(num, '08b') pads the binary string with leading zeros to ensure it's a specific length. This is incredibly useful for aligning data or working with fixed-width protocols where you need a full byte representation.

Converting binary strings back to integers

binary_string = "101010"
num = int(binary_string, 2) # 2 is the base
print(f"The binary {binary_string} converted to decimal is: {num}")--OUTPUT--The binary 101010 converted to decimal is: 42

To reverse the process, you can use Python's built-in int() function. While it's commonly used for simple string-to-integer conversions, its second argument lets you specify the number's base. This is how you turn a binary string back into a decimal number.

  • The first argument, "101010", is the binary string you're converting.
  • The second argument, 2, tells the function to interpret the string as a base-2 number, which is the key to the conversion.

Advanced binary operations

With string conversions handled, you can now interact with binary data more directly through literals, bitwise operations, and specialized objects like bytes and bytearray.

Using binary literals in Python

binary_literal = 0b101010 # Binary literal for 42
octal_literal = 0o52 # Octal literal for 42
hex_literal = 0x2A # Hexadecimal literal for 42
print(f"Values: {binary_literal}, {octal_literal}, {hex_literal}")--OUTPUT--Values: 42, 42, 42

Python lets you write integers directly in your code using different number systems. By prefixing a value with 0b, as in 0b101010, you're telling the interpreter it's a binary number. Unlike the string from bin(), this binary literal is immediately recognized and stored as a standard integer—in this case, 42.

  • This is especially handy for tasks like setting configuration flags or working with bitmasks, where the binary layout is more meaningful than the decimal value.
  • Python extends this concept to other bases, using 0o for octal and 0x for hexadecimal numbers, giving you flexibility in how you represent data.

Converting to binary using bitwise operations

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

print(int_to_binary(42))--OUTPUT--101010

For more control, you can build a custom function like int_to_binary() using bitwise operations. This approach manually constructs the binary string bit by bit, offering a deeper understanding of the conversion process itself.

  • The function's core is a while loop that continues as long as the number is greater than zero.
  • Inside the loop, num & 1 uses the bitwise AND operator (&) to isolate the rightmost bit.
  • After extracting the bit, num >>= 1 performs a right bit shift, moving every bit one position to the right and preparing the next bit for the following iteration.

Working with bytes and bytearray objects

num = 42
# Convert integer to 4-byte representation
byte_representation = num.to_bytes(4, byteorder='big')
# Convert back to integer
original_num = int.from_bytes(byte_representation, byteorder='big')
print(f"Bytes: {byte_representation}")
print(f"Back to number: {original_num}")--OUTPUT--Bytes: b'\x00\x00\x00*'
Back to number: 42

For low-level tasks like networking or file I/O, you'll often use bytes and bytearray objects. The to_bytes() method converts an integer into a fixed-size sequence of bytes. For instance, num.to_bytes(4, byteorder='big') transforms the number 42 into a specific 4-byte representation.

  • The first argument, 4, dictates the total number of bytes in the output.
  • The byteorder='big' argument is crucial for consistency, as it defines how bytes are ordered from most significant to least significant.

To reverse the operation, you can use int.from_bytes(). It's a straightforward way to turn the byte sequence back into an integer, as long as you specify the same byte order.

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. You don't need to configure environments or manage packages.

While knowing individual techniques like bin() and bitwise operations is useful, Agent 4 helps you go from piecing them together to building complete applications. It takes your description and handles the code, databases, APIs, and deployment.

Instead of building from scratch, you can describe the tool you want Agent to build. For example:

  • A network packet analyzer that uses to_bytes() to construct data packets for testing communication protocols.
  • A permissions calculator that uses bitwise operations to set and read access flags from a single integer.
  • A custom number system converter that uses format() to display binary, octal, and hex values with zero-padding for alignment.

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

Common errors and challenges

When converting numbers to binary, you might run into a few common pitfalls that can lead to bugs or unexpected behavior.

  • Forgetting the base in int(). A frequent mistake is forgetting to specify the base when using the int() function to convert a binary string back to a number. If you call int("101010") without the second argument, Python assumes it's a base-10 number and returns the integer 101010, not 42. Always remember to include 2 as the second argument, like int("101010", 2), to tell the function it's working with a binary value.
  • Misusing bitwise operators. Bitwise operations can also be tricky due to operator precedence, which dictates the order of operations. Without parentheses, an expression involving bitwise operators like &, |, or ^ might not evaluate as you expect, leading to incorrect results. It's best practice to use parentheses to explicitly group your operations, ensuring your logic is clear and executes in the intended order.
  • Mishandling fixed-width formatting. When using format() for fixed-width binary strings, it's important to understand how padding works. If you try to format a number that requires more bits than your specified width—for example, formatting 256 as an 8-bit string—format() won't truncate the value. Instead, it will return the full binary representation, which can break systems that expect a strict, fixed-width input.

Forgetting to specify the base when converting binary strings with int()

It's an easy mistake to make. When converting a binary string back to a number with int(), forgetting the second argument causes Python to assume it's a standard base-10 number. The result isn't a conversion—it's a misinterpretation. The code below shows this in action.

binary_string = "101010"
num = int(binary_string) # Missing the base parameter
print(f"The binary {binary_string} converted to decimal is: {num}")

Without a second argument, the int() function defaults to interpreting the string as a decimal number. This common oversight leads to a logical error, not a syntax one. The following code demonstrates the simple correction.

binary_string = "101010"
num = int(binary_string, 2) # 2 is the base for binary
print(f"The binary {binary_string} converted to decimal is: {num}")

The fix is simple: always provide the base as the second argument to the int() function. By using int("101010", 2), you explicitly tell Python to interpret the string as a base-2 number, ensuring the correct conversion. It's a common mistake to forget this argument, especially when parsing data from files or network streams where binary values are often represented as strings. Without it, Python defaults to base-10, leading to logical errors.

Incorrectly applying bitwise operators (&, |, ^) without parentheses

Incorrectly applying bitwise operators (&, |, ^) without parentheses

Bitwise operators like &, |, and ^ follow a strict order of operations that isn't always intuitive. If you don't use parentheses to group them, your code might run without errors but produce the wrong answer. The code below shows what happens.

a = 0b1010
b = 0b1100
result = a & b | a ^ b # Ambiguous operation order
print(f"Result: {bin(result)}")

Python's operator precedence rules cause the & operation to run before |, which can produce an incorrect result if your logic requires a different sequence. The code below demonstrates how to enforce the intended order.

a = 0b1010
b = 0b1100
result = (a & b) | (a ^ b) # Clear operation order with parentheses
print(f"Result: {bin(result)}")

By wrapping operations in parentheses, as in (a & b) | (a ^ b), you enforce a clear order of evaluation. This removes any ambiguity from operator precedence and ensures your logic runs exactly as intended. It's a crucial practice whenever you combine bitwise operators like &, |, or ^ in a single expression. This simple step prevents subtle bugs and makes your code's intent obvious, especially when working with complex bitmasks or flags.

Losing data in fixed-width binary conversion with format()

Using format() for fixed-width binary strings can be misleading. It won’t truncate a number that’s too large for the specified width. Instead, it returns the full value, which can cause errors in systems expecting fixed-length data. The following code demonstrates the issue.

large_num = 1024
binary = format(large_num, '08b') # Only 8 bits, but number needs 11 bits
print(f"Binary representation: {binary}")

The number 1024 requires more bits than the specified eight. Instead of truncating the value, format() returns the full binary string, which can cause silent data overflow. The following code demonstrates how to handle this properly.

large_num = 1024
min_width = large_num.bit_length()
binary = format(large_num, f'0{min_width}b') # Dynamic width based on number
print(f"Binary representation: {binary}")

To prevent silent data overflow, you can dynamically set the padding width. The bit_length() method calculates the minimum number of bits needed for an integer. You can then use an f-string, like f'0{min_width}b', within the format() function to ensure the binary string is always the correct length. This approach is crucial when handling numbers of varying sizes, as it prevents your formatted output from being unexpectedly longer than planned.

Real-world applications

Beyond theory, these operations are key to real-world tasks, from setting permissions with bit flags to extracting colors with bitwise operators.

Using bit flags for permission settings

You can use bit flags to efficiently manage multiple on/off states, like user permissions, by packing them into a single integer.

# Define permission flags
READ = 0b100 # 4
WRITE = 0b010 # 2
EXECUTE = 0b001 # 1

# Set permissions (read and execute)
user_permissions = READ | EXECUTE
print(f"User permissions: {bin(user_permissions)}")

# Check if user has write permission
has_write = bool(user_permissions & WRITE)
print(f"Has write permission: {has_write}")

This code uses binary literals to define unique permission flags where each flag represents a single bit. It demonstrates two key bitwise operations:

  • The bitwise OR operator (|) combines permissions. For example, READ | EXECUTE creates a new value that includes both flags.
  • The bitwise AND operator (&) checks for a specific permission. The expression user_permissions & WRITE isolates the write bit, and bool() converts the result to a simple True or False.

Extracting RGB color channels with bitwise & and >>

Bitwise operators like the right shift (>>) and AND (&) are also ideal for digital color manipulation, letting you pull individual red, green, and blue values from a single integer color code.

# RGB color value (Tomato color)
color_value = 0xFF6347

# Extract RGB components
red = (color_value >> 16) & 0xFF
green = (color_value >> 8) & 0xFF
blue = color_value & 0xFF

print(f"Color: #{color_value:06X}")
print(f"RGB: Red={red}, Green={green}, Blue={blue}")

This technique unpacks a single integer color value into its separate red, green, and blue components using bitwise operations. It’s a common and efficient way to handle color data.

  • The right shift operator >> moves the bits for a specific color channel into the rightmost position. For example, >> 16 shifts the red value into place.
  • The bitwise AND operator & with 0xFF then acts as a mask, isolating those 8 bits to get the final channel value from 0 to 255.

This process is repeated for each channel, with the blue value requiring no shift since it's already in the last 8 bits.

Get started with Replit

Put your knowledge into practice and create a real tool with Replit Agent. Describe what you want, like “a number system converter with padded binary output” or “a permissions calculator using bit flags.”

Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit and see your tool work in minutes.

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.

Get started for free

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.