Python
Integer Conversion
Binary
Programming
Python Tips

Converting integer to binary in Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Binary conversion is a small task that shows up everywhere from interview questions to protocol work, bit masks, and debugging packed values. Python makes the common case easy, but it is still worth understanding what the built-in tools return and when you need a fixed-width representation instead.

The Fastest Way: bin()

Python ships with bin(), which converts an integer to a binary string. The returned value includes the 0b prefix so you can tell which base is being used.

python
1numbers = [5, 42, 255]
2
3for n in numbers:
4    print(n, "->", bin(n))

Output:

text
5 -> 0b101
42 -> 0b101010
255 -> 0b11111111

If you need only the digits, slice off the prefix:

python
n = 42
binary_digits = bin(n)[2:]
print(binary_digits)

This is the idiomatic solution for general Python code. It is readable, fast enough for normal applications, and it works for arbitrarily large integers because Python integers are not limited to 32 or 64 bits.

Formatting Binary Strings

The format() function gives you more control. It is useful when you want padding, alignment, or when you are building strings for logs or reports.

python
1n = 13
2
3print(format(n, "b"))      # 1101
4print(format(n, "08b"))    # 00001101
5print(f"{n:b}")            # 1101
6print(f"{n:08b}")          # 00001101

The format specifier "b" means binary. Adding a width such as "08b" pads with leading zeroes until the result is eight characters wide. That is often exactly what you want when showing bytes, permission masks, or small hardware values.

Fixed-Width Binary and Negative Numbers

Negative integers are where developers usually get surprised. Python does not automatically truncate integers to eight, sixteen, or thirty-two bits, so bin(-5) returns a signed string:

python
print(bin(-5))

That prints -0b101, which is mathematically correct but not the same as a two's-complement machine representation. If you need a fixed-width binary value, mask the number first.

python
1def to_twos_complement(value: int, bits: int) -> str:
2    mask = (1 << bits) - 1
3    return format(value & mask, f"0{bits}b")
4
5print(to_twos_complement(-5, 8))
6print(to_twos_complement(-5, 16))

Output:

text
11111011
1111111111111011

This pattern matters when you are working with binary protocols, cryptography exercises, or file formats that assume a fixed register width. Without masking, the result reflects Python's integer model, not the target machine format.

Writing the Conversion Yourself

Sometimes the goal is not just to get the answer, but to understand the algorithm. A manual conversion repeatedly divides by two and records the remainders.

python
1def int_to_binary(n: int) -> str:
2    if n == 0:
3        return "0"
4    if n < 0:
5        return "-" + int_to_binary(-n)
6
7    digits = []
8    while n > 0:
9        digits.append(str(n % 2))
10        n //= 2
11
12    return "".join(reversed(digits))
13
14print(int_to_binary(19))
15print(int_to_binary(-19))

That function is useful for teaching, but it is usually not the best production choice. bin() and format() are clearer to most Python developers and less likely to hide off-by-one mistakes.

Choosing the Right Approach

Use bin() when you simply need a binary representation quickly. Use format() or f-strings when width and presentation matter. Use masking when the output must represent a fixed number of bits. Write the conversion manually only when you are practicing the algorithm or implementing a custom numeric format.

One final detail is parsing in the opposite direction. Python can also convert a binary string back to an integer with int(text, 2):

python
binary_text = "101010"
value = int(binary_text, 2)
print(value)

That makes it easy to move between human-readable binary strings and regular numeric values in tests and tooling.

Common Pitfalls

The first pitfall is forgetting about the 0b prefix returned by bin(). If you compare the result to a plain digit string, strip the first two characters or use format(n, "b") instead.

Another common mistake is assuming negative values will automatically appear in two's-complement form. Python does not impose a fixed bit width, so you need to choose one explicitly and mask the value.

Padding is another source of bugs. If a network packet expects eight bits and you send "101", you may end up writing the wrong value downstream. Use a width specifier such as "08b" whenever the field size is part of the protocol.

Summary

  • 'bin(n) is the simplest built-in way to convert an integer to binary in Python.'
  • 'format(n, "b") and f-strings are better when you need padding or layout control.'
  • Negative numbers require masking if you want a fixed-width two's-complement representation.
  • Manual conversion is helpful for learning, but built-in functions are usually the best production choice.
  • Use int(binary_text, 2) when you need to convert binary digits back into an integer.

Course illustration
Course illustration

All Rights Reserved.