binary conversion
integer to binary
programming tutorial
binary string
number systems

Changing integer to binary string of digits

Master System Design with Codemia

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

Introduction

Converting an integer to a binary string is a small task that shows up in debugging, bit manipulation, protocol work, and interview questions. Most languages already have a built-in conversion function, but it still helps to understand the manual algorithm so you can handle special cases such as zero, negative values, and fixed-width output correctly.

Core Sections

What binary conversion really means

A binary string represents a number in base 2 rather than base 10. Each digit position is a power of two, so decimal 18 becomes binary 10010 because:

  • '16 is 2^4'
  • '2 is 2^1'
  • '16 + 2 = 18'

The classic manual algorithm repeatedly divides the number by 2, records the remainder, and then reverses the collected remainders.

For 18:

  • '18 / 2 remainder 0'
  • '9 / 2 remainder 1'
  • '4 / 2 remainder 0'
  • '2 / 2 remainder 0'
  • '1 / 2 remainder 1'

Reading those remainders from bottom to top gives 10010.

A manual implementation

The manual approach is useful when you want to understand the mechanics or implement the logic in a language without a convenient helper.

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

This version treats negative numbers as a sign plus the binary magnitude. That is often what people want in application-level code, but it is not the same as a machine-width two's-complement representation.

Built-in conversion is usually better in production

For ordinary application code, the built-in conversion function is usually clearer and less error-prone.

python
print(bin(18))       # 0b10010
print(bin(18)[2:])   # 10010

Other languages offer similar helpers.

javascript
console.log((18).toString(2));
csharp
int n = 18;
string bits = Convert.ToString(n, 2);
Console.WriteLine(bits);

The built-in approach is usually the right choice unless you need custom formatting rules or are deliberately implementing the algorithm yourself.

Negative numbers and two's complement

This is where confusion starts. There are at least two reasonable meanings for "binary string of a negative integer":

  • a human-readable sign plus magnitude, such as -101
  • a fixed-width two's-complement view, such as 11111011 for -5 in 8 bits

Python’s bin(-5) returns -0b101, which is the sign-plus-magnitude style. If you need the machine-style bit pattern, mask the value first.

python
1def to_twos_complement_8bit(n: int) -> str:
2    return format(n & 0xff, "08b")
3
4
5print(to_twos_complement_8bit(-5))
6print(to_twos_complement_8bit(5))

That distinction matters in systems code, networking, and file formats. If you do not define the expected negative-number format up front, the function contract stays ambiguous.

Fixed-width output and padding

Many use cases do not want a minimal-length binary string. They want a fixed number of digits, often padded with leading zeroes.

python
1def to_binary_padded(n: int, width: int) -> str:
2    return format(n, f"0{width}b")
3
4
5print(to_binary_padded(5, 8))
6print(to_binary_padded(18, 8))

This is common for protocol fields, register dumps, and teaching materials. The important design choice is what to do when the number does not fit the requested width. A safe function should document whether it expands the output, truncates, or raises an error.

When performance matters

For almost all business code, conversion cost is negligible. If you are converting millions of values, built-ins are usually faster than hand-written logic, and they are easier to optimize by the runtime.

If you do implement the loop yourself, avoid repeated string concatenation inside the loop. Collect digits in a list and join once, as shown earlier. That keeps the algorithm linear in the number of bits rather than creating unnecessary string copies.

Common Pitfalls

  • Forgetting to handle 0 often produces an empty string instead of 0.
  • Assuming a negative value should automatically be shown in two's complement creates incorrect output for APIs that expect a sign-prefixed value.
  • Using a fixed-width formatter without deciding what happens on overflow can silently corrupt data.
  • Reimplementing conversion manually in production code when a built-in helper exists adds risk without much benefit.
  • Mixing sign-magnitude formatting and two's-complement formatting in one code path makes the function contract unclear.

Summary

  • Binary conversion can be done manually or with built-in helpers.
  • The manual algorithm uses repeated division by 2 and reversed remainders.
  • Built-ins are usually the better production choice.
  • Negative-number formatting must be defined explicitly because sign format and two's complement are different outputs.
  • Fixed-width binary strings are common in protocol and systems work and need deliberate overflow rules.

Course illustration
Course illustration

All Rights Reserved.