How to convert a number to binary in Python
Discover multiple ways to convert numbers to binary in Python. Explore tips, applications, and how to debug common conversion errors.

Python developers often need to convert numbers to their binary representation. The language offers built-in tools like the bin() function that make this process simple and efficient for various applications.
In this article, you'll learn several techniques for binary conversions. You'll get practical tips, explore real-world applications, and receive clear advice to help you fix any 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 the most direct method for converting an integer into its binary string equivalent. The function returns a string that always starts with the prefix 0b, which is Python's standard notation for identifying a binary literal.
This prefix is useful for clarity, but you may need to remove it depending on your use case. The output 0b101010 can be understood as two parts:
0b: The prefix indicating the value is a binary number.101010: The actual binary representation of the integer 42.
Working with binary strings
Working with the raw output from bin() often involves removing the prefix, applying custom formats with format(), or converting the string back to 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
Because bin() returns a string, you can easily remove the prefix using string slicing. The slice notation [2:] tells Python to create a new string starting from the character at index 2, which neatly cuts off the leading 0b.
- This method is efficient and widely used for its simplicity.
- It gives you a clean binary string like
101010, ready for further processing or display.
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 convert integers to binary, giving you the representation directly without the 0b prefix. This can simplify your code compared to slicing the output of bin(). The function's real power, however, lies in its format specifiers, which let you control the output's appearance.
- For example, the specifier in
format(num, '08b')pads the binary string with leading zeros to ensure it's 8 digits long. - This is especially useful when you're working with data that needs a fixed-width representation, like a byte.
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 converting strings to integers, it also accepts a second argument to specify the number's base. This makes it perfect for handling binary, octal, or hexadecimal strings.
- By passing
2as the second argument, you're telling Python that the string"101010"is a base-2 number. - The function then correctly interprets the string and returns its decimal equivalent, which is
42.
Advanced binary operations
Beyond string manipulation, Python offers more direct ways to work with binary data, including using binary literals, bitwise operators, 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
You can write numbers directly in binary within your code using literals. Python recognizes the 0b prefix as an instruction to interpret the value as a base-2 number. So, when you write 0b101010, Python treats it exactly the same as the integer 42. This approach is especially handy when your code deals with bit-level operations or hardware interactions where binary is more intuitive.
- The
0bprefix denotes a binary literal. - This concept also applies to other bases, like
0ofor octal and0xfor hexadecimal.
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 a more fundamental approach, you can build a binary string using bitwise operators. This custom int_to_binary() function works by repeatedly inspecting the number's bits and constructing the string from right to left.
- The core of the logic is the bitwise AND operation,
num & 1, which isolates the last bit of the number, resulting in either a 0 or 1. - Next, the bitwise right shift,
num >>= 1, moves every bit one position to the right. This effectively divides the number by two and prepares the next bit for inspection.
The loop continues until the original number becomes zero, leaving you with the complete binary representation.
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
When you're dealing with raw binary data for tasks like file I/O or networking, Python’s bytes and bytearray objects are essential. The to_bytes() method converts an integer into a fixed-size sequence of bytes, which is how data is often structured in lower-level applications.
- You specify the byte length and the
byteorder—'big'means the most significant byte is first. - To convert back, the
int.from_bytes()method reconstructs the original integer from the byte sequence.
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 interprets raw
bytesand displays packet information. - Create a bitwise calculator that lets you experiment with operators like
&and>>in real time. - Deploy a universal base converter that uses functions like
bin()andformat()to switch between decimal, binary, and hex.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
Even with Python's straightforward tools, you might run into a few common pitfalls when converting numbers to binary.
- Forgetting to specify the base when converting binary strings with
int(). If you pass a binary string toint()without specifying the base, Python assumes it's a base-10 number, which will lead to incorrect results. Always include the second argument,2, likeint("101010", 2), to ensure the string is interpreted correctly as binary. - Incorrectly applying bitwise operators (
&,|,^) without parentheses. Bitwise operators have a lower precedence than comparison operators, which can cause unexpected behavior in your logic. For instance, an expression likenum & 1 == 1is evaluated asnum & (1 == 1). Always use parentheses, such as(num & 1) == 1, to enforce the correct order of operations. - Losing data in fixed-width binary conversion with
format(). It's a common misconception thatformat()will truncate a number to fit a specified width. The function only pads with zeros—if the number's binary form is longer than the width,format()returns the full string. This can cause bugs if your code expects a strictly fixed-width input, so you'll need to handle any necessary truncation manually.
Forgetting to specify the base when converting binary strings with int()
A frequent mistake is forgetting to tell the int() function you're working with a binary string. By default, it assumes the string is a standard base-10 number, leading to wildly incorrect results and subtle bugs that can be tricky to spot.
The code below shows what happens when you pass a binary string to int() without specifying the base.
binary_string = "101010"
num = int(binary_string) # Missing the base parameter
print(f"The binary {binary_string} converted to decimal is: {num}")
Since the base isn't specified, int() processes "101010" as a standard decimal number, resulting in one hundred one thousand and ten. The correct implementation is shown in the next example.
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. By calling int("101010", 2), you're telling Python to treat the string as a base-2 number, which correctly yields the integer 42. You'll need to be mindful of this whenever your code handles binary strings from external sources, like files or network data. Forgetting this second argument is a common source of bugs because Python will otherwise assume the string is a standard decimal number.
Incorrectly applying bitwise operators (&, |, ^) without parentheses
A common pitfall is assuming bitwise operators are evaluated from left to right. Python's precedence rules can make expressions with multiple operators like &, |, and ^ ambiguous, leading to silent bugs. The following code demonstrates what happens when the order isn't explicitly controlled.
a = 0b1010
b = 0b1100
result = a & b | a ^ b # Ambiguous operation order
print(f"Result: {bin(result)}")
The expression is ambiguous because Python evaluates the bitwise & and ^ operators before |. This can produce an unexpected result if you intended a different order. See how to clarify your intent in the code below.
a = 0b1010
b = 0b1100
result = (a & b) | (a ^ b) # Clear operation order with parentheses
print(f"Result: {bin(result)}")
The solution is to wrap each part of the expression in parentheses. Writing (a & b) | (a ^ b) forces Python to evaluate the & and ^ operations first, before combining their results with |. This simple habit removes any doubt about the order of operations.
You should always use parentheses when mixing bitwise operators like &, |, and ^ to prevent subtle bugs caused by Python's precedence rules.
Losing data in fixed-width binary conversion with format()
When using format() for fixed-width binary strings, you might expect it to truncate larger numbers. However, the function doesn't cut off data. It returns the full binary representation, ignoring the width you set. The code below shows what happens.
large_num = 1024
binary = format(large_num, '08b') # Only 8 bits, but number needs 11 bits
print(f"Binary representation: {binary}")
The code requests an 8-bit string, but the number 1024 needs 11 bits. Since format() doesn't truncate the output, you get a longer string than expected, which can break systems relying on fixed-width data. See how to handle this.
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}")
The fix is to calculate the width dynamically. The bit_length() method returns the minimum number of bits needed for an integer. You can then use an f-string, like f'0{min_width}b', inside the format() function to create a format specifier on the fly. This guarantees the binary string has the correct padding for its size, which is essential when dealing with systems that require precise data widths, like network protocols or file formats.
Real-world applications
With a solid grasp of binary conversion, you can tackle practical challenges like managing system permissions or manipulating individual color channels.
Using bit flags for permission settings
Bit flags offer an efficient way to manage multiple permissions, such as read and write access, by combining them into a single integer that you can check using bitwise operators like & and |.
# 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 defines each permission—READ, WRITE, and EXECUTE—as a unique binary number where only one bit is active. This setup ensures that no two permissions overlap.
- The bitwise OR operator,
|, combines theREADandEXECUTEflags into a single integer, effectively granting both permissions at once. - To verify access, the code uses the bitwise AND operator,
&. The expressionuser_permissions & WRITEchecks if the "write" bit is enabled. - Since it isn't, the result is zero, which
bool()converts toFalse.
Extracting RGB color channels with bitwise & and >>
Bitwise operators like the right shift >> and bitwise AND & are also perfect for digital color manipulation, allowing you to extract individual red, green, and blue channels from a single packed integer.
# 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 code unpacks a single hexadecimal integer into its separate red, green, and blue components. Since each color channel is an 8-bit value, bitwise operations are perfect for this.
- The right shift operator,
>>, moves the bits of the target channel to the rightmost position. For example,>> 16shifts the red component. - The bitwise AND operator,
&, is then used with the mask0xFFto isolate the 8 bits of the channel, effectively extracting its value. The blue channel doesn't need a shift since it's already in the correct position.
Get started with Replit
Turn what you've learned into a real tool. Tell Replit Agent to “build a universal base converter” or “create a bitwise calculator that visualizes operations.”
The agent writes the code, tests for errors, and deploys your app automatically. 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.



.png)