Convert Decimal to Binary in Python

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Base conversion

What you’ll learn

  • How division by two and remainders produce binary digits from right to left.
  • Why you must handle zero and why the first method reverses collected bits.
  • A second method using bit scan, plus a live preview.

Overview

Binary uses powers of two. To convert a nonnegative decimal integer into binary, repeatedly divide by 2 and track remainders 0 or 1.

Two methods

Remainder collection and bit-scan.

Live preview

Test quickly with safe integer input.

Inverse

Pair with binary-to-decimal.

Prerequisites

Basic loops, modulo, integer division, and string joining in Python.

  • // for integer division and % for remainder.
  • Optional: bit operations like >> and &.

Decimal to binary

Each binary digit is a coefficient on a power of two. Repeatedly taking n % 2 gives bits from least significant to most significant.

Example: 15 = 8 + 4 + 2 + 1, so binary is 1111.

Decimalbase 10
Binarybase 2
Example15 → 1111

Division algorithm

For n ≥ 0, repeatedly write n = 2q + r with r in {0,1}. The remainders form binary digits from right to left.

15

15→7 r1, 7→3 r1, 3→1 r1, 1→0 r1 so binary is 1111.

Intuition

81000₂
Power
2^3
5101₂
Sum
4 + 1

Takeaway: each division step answers odd/even at the current scale.

Live Preview

Nonnegative integers in JavaScript safe range.

Live result
Press "Show binary" to convert.

Algorithm (remainder method)

Goal: output binary string of nonnegative n.

Handle n == 0

Return "0".

Collect bits

Append n % 2, then do n //= 2 until n becomes 0.

Reverse

Reverse collected bits and join.

📜 Pseudocode

Pseudocode
function decimal_to_binary(n):
    if n == 0:
        return "0"
    bits = []
    while n > 0:
        bits.append(n % 2)
        n = n // 2
    reverse(bits)
    return join(bits)
1

Divide by two and reverse bits

Classic approach: collect remainder bits, then reverse to print MSB-first.

python
def decimal_to_binary(n: int) -> str:
    if n == 0:
        return "0"

    bits: list[str] = []
    while n > 0:
        bits.append(str(n % 2))
        n //= 2

    bits.reverse()
    return "".join(bits)


print(decimal_to_binary(15))  # 1111
print(decimal_to_binary(0))   # 0

Explanation

Remainders are collected from least significant bit to most significant bit, so reversing is required for normal output.

2

Bit-scan from MSB to LSB

No reversal buffer needed. Start at highest set bit and read downward.

python
def to_binary_bit_scan(n: int) -> str:
    if n == 0:
        return "0"

    highest = n.bit_length() - 1
    out: list[str] = []

    for b in range(highest, -1, -1):
        bit = (n >> b) & 1
        out.append("1" if bit else "0")

    return "".join(out)


print(to_binary_bit_scan(15))  # 1111
print(to_binary_bit_scan(64))  # 1000000

Explanation

bit_length() finds the highest bit position so you can scan MSB to LSB directly.

Optimization

Built-in fast path. For nonnegative integers, format(n, "b") or bin(n)[2:] is concise and reliable.

Fixed width. Use format specifiers like format(n, "08b") when padding is required.

Interview: explain remainder logic first, then mention bit-scan or built-ins.

❓ FAQ

The first remainder from n/2 is the least significant bit (parity). Each later remainder is the next higher bit. Printing from last remainder to first gives MSB to LSB.
The loop while n > 0 will not run, so you must handle n == 0 separately and return '0'.
It checks bits from a high position down to 0 and skips leading zeros. This avoids storing all remainders first.
For learning conversion, many tutorials restrict to nonnegative numbers. If you need signed representation, document whether you use absolute value or fixed-width two's complement.
Either minimal bits (no leading zeros) or fixed width like 8/16/32 bits, depending on problem requirements.
O(b) where b is number of output bits. For positive n, that's O(log2 n) in the remainder method.

🔄 Input / output examples

Use these values to verify both approaches.

DecimalBinary (minimal)
00
11
151111
641000000

Edge cases and pitfalls

Handle zero explicitly and define behavior for negatives before coding.

Zero

n == 0

Return "0"; otherwise a plain while n > 0 loop returns empty output.

Negative

Policy choice

Choose absolute-value conversion or fixed-width two's complement and document it clearly.

Width

Minimal vs padded

Some tasks expect 00001111 instead of 1111; padding rules matter.

Inverse

Binary to decimal

Practice the reverse conversion too for interview completeness.

⏱️ Time and space complexity

ApproachTimeExtra space
Remainder + reverseO(log n)O(log n)
Bit scan using bit_lengthO(log n)O(log n)

log is base 2 in bit-length terms for positive n.

Summary

  • Use remainder and division by 2 to build bits.
  • Always handle n == 0 separately.
  • Bit scan gives a neat MSB-to-LSB alternative.
Did you know?

Repeated division by 2 collects bits from least to most significant, so the usual classroom program prints the array backwards. A bit-scan loop can print from the MSB without an explicit reversal.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful