Convert Decimal to Binary in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Base conversion

What You’ll Learn

Decimal-to-binary conversion turns a base-10 integer into a base-2 bit string. This tutorial covers remainders, bit scan, built-ins, a live preview, worked Python examples, edge cases, and complexity.

Powers of Two

Base 2

Each bit is a coefficient on 1, 2, 4, 8…

Remainders

n % 2

Collect bits LSB-first, then reverse for MSB-first output.

Bit Scan

MSB → LSB

Read bits from the highest set position downward.

Handle Zero

Special case

Return "0" — a plain while n > 0 loop would print nothing.

Live Preview

Try any n

Convert nonnegative integers instantly in the browser.

O(log n)

Complexity

Output length is about the bit length of n.

Introduction

Decimal-to-binary conversion writes a nonnegative integer using only bits 0 and 1. Classic example: 15 = 8 + 4 + 2 + 1 → binary 1111.

The classroom method divides by 2 and stacks remainders (LSB first), then reverses. A bit-scan or format(n, "b") can produce the same string more directly.

Why it matters?

It trains place value, loops, bit thinking, and the habit of handling zero and width rules in interviews.

Key Highlights

LSB First

First remainder is the rightmost bit.

Reverse to Print

MSB-first output needs a reverse (or bit scan).

Zero Guard

Always return "0" for input 0.

Built-ins Exist

bin / format after you know the theory.

In short: repeatedly take n % 2 and n //= 2, reverse the bits (or scan from the MSB), and special-case zero.

📝 Problem & Approach

Given a nonnegative integer n, return its binary representation as a string (minimal bits, no leading zeros except for 0).

python
# 15 → remainders 1,1,1,1 → reverse → "1111"
# 8  → "1000"
# 0  → "0"

Inputs & Outputs

ItemTypeDescription
nintNonnegative integer (define policy for negatives).
Return / printstrBinary digits as a string, e.g. "1111".

Minimal workflow

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)

Method comparison

MethodIdeaNotes
Remainder + reverseCollect n % 2, then reverseBest classroom / interview explanation
Bit scanMSB down to bit 0 with >> and &No reverse step
Built-informat(n, "b") / bin(n)[2:]Idiomatic production Python

⚡ Quick Reference

GoalPattern
Next bitn % 2
Shift right (divide)n //= 2
MSB-first outputbits.reverse() or scan high→low
Zero caseif n == 0: return "0"
Built-informat(n, "b")
Padded widthformat(n, "08b")

📋 Remainder vs Bit Scan vs Built-in

Same binary string — different clarity and interview signaling.

Remainder
% 2 + reverse

Shows place-value / division clearly

Bit scan
>> and &

MSB-first without an explicit reverse

Built-in
format / bin

Shortest production style

Interview tip
remainders first

Explain loops, then mention built-ins

Context

When This Problem Shows Up

Reach for decimal-to-binary drills when base conversion and bits matter.

  1. Interview warm-ups

    Checks loops, modulo, and LSB vs MSB understanding.

  2. Teaching place value

    Makes powers of two concrete with 15 → 1111.

  3. Gateway to other bases

    Same remainder idea extends to octal and hex.

  4. Systems / bit intros

    Binary strings show up in flags, masks, and networking topics.

  5. Not for floats alone

    Fractional binaries need a different place-value story after the point.

Key benefit: one short problem that covers remainders, bit order, zero handling, and O(log n) reasoning.

🔮 Live Preview

Nonnegative integers in JavaScript safe range.

Try 0, 8, 15, or 64.

Live result
Press "Show binary" to convert.

Examples Gallery

Three complete Python programs — remainder + reverse, bit scan, and built-in formatting. Click View Output to reveal sample console results.

📚 Getting Started

Classic divide-by-two approach — collect, then reverse.

Example 1 — Divide by Two and Reverse Bits

Collect remainder bits LSB-first, 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

How It Works

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

⚡ Bit Operations

Scan from the highest set bit downward — no reverse buffer.

Example 2 — Bit-Scan from MSB to LSB

Use bit_length() to find the top bit, then read each bit with shifts.

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

How It Works

bit_length() finds the highest bit position so you can scan MSB to LSB directly with (n >> b) & 1.

🚀 Idiomatic Python

Same answer with built-ins — great after you know the algorithm.

Example 3 — Using format / bin

Minimal bits or fixed-width padding in one call.

python
def to_binary_builtin(n: int) -> str:
    if n < 0:
        raise ValueError("This helper expects a nonnegative integer")
    return format(n, "b")


print(to_binary_builtin(15))
print(to_binary_builtin(0))
print(format(15, "08b"))  # padded to 8 bits
print(bin(64)[2:])        # strip the '0b' prefix

How It Works

format(n, "b") is the cleanest minimal-bit conversion. Width specs like "08b" add leading zeros when a problem asks for fixed width.

🧠 How the Algorithm Converts

1

Handle zero

If n == 0, return "0" immediately.

Guard
2

Collect bits

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

Loop
3

Reverse / join

Reverse the list (or have scanned MSB-first) and join into a string.

Format
=

Binary string

Return the MSB-first bit string — that is the base-2 form of n.

🔎 Worked Walkthrough — n = 15

Trace the remainder method. Bits collect LSB-first, then reverse.

nn % 2n // 2bits so far
1517[1]
713[1, 1]
311[1, 1, 1]
110[1, 1, 1, 1]

Reverse → 1111. Check: 8 + 4 + 2 + 1 = 15.

Use Cases

Where decimal-to-binary conversion shows up beyond the interview prompt.

1. Interview Warm-Ups

Tests remainder loops and bit-order fluency.

Example: write decimal_to_binary(n).

2. Teaching Powers of Two

Makes 1, 2, 4, 8… concrete with 15 → 1111.

Example: chalkboard place values.

3. Flags / Masks

Bit strings help explain packed options.

Example: print permission bits.

4. Gateway to Octal / Hex

Same remainder idea with base 8 or 16.

Example: next page — decimal to octal.

5. Round-Trip Practice

Pair with binary-to-decimal for inverse checks.

Example: assert int(bits, 2) == n.

6. Fixed-Width Output

Pad to 8/16/32 bits when a protocol requires it.

Example: format(n, "08b").

Pro Tip: say “first remainder is LSB” before coding — it prevents forgetting the reverse.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Math Maps Cleanly

    Remainders are exactly the binary digits.

  2. 2. Easy Built-in Shortcut

    format(n, "b") keeps application code short after the theory.

  3. 3. Clear Complexity

    O(log n) steps and O(log n) output space are easy to argue.

  4. 4. Transferable Pattern

    Same method works for octal, hex, and custom bases.

Pro Tip: prepend bits with bits.insert(0, …) if you want to avoid an explicit reverse — still explain LSB order.

Usage Tips

Small habits that keep decimal-to-binary solutions interview-ready.

  1. 1. Special-Case Zero

    Return "0" before the remainder loop.

  2. 2. Say LSB First Out Loud

    Then reverse (or bit-scan) for MSB-first print.

  3. 3. Spot-Check 15 and 8

    Expect 1111 and 1000 as golden tests.

  4. 4. Clarify Width

    Ask whether minimal bits or padded width is required.

  5. 5. Mention Built-ins Second

    Show the loop first; then format(n, "b").

Pro Tip: round-trip with int(bits, 2) to catch reverse mistakes instantly.

Common Pitfalls

Mistakes that commonly break decimal-to-binary solutions.

  1. 1. Forgetting to Reverse

    Printing remainders in collection order reverses the bits.

    → Reverse the list (or insert at front / bit-scan).

  2. 2. Empty Output for Zero

    while n > 0 never runs when n is 0.

    → Return "0" explicitly.

  3. 3. Silent Negatives

    Python // and % on negatives need a defined policy.

    → Reject or document abs / two’s complement.

  4. 4. Wrong Width Assumption

    Some graders expect padded 8-bit strings.

    → Ask whether minimal or fixed width is required.

  5. 5. Leaving the 0b Prefix

    bin(n) returns 0b... which often fails string checks.

    → Use bin(n)[2:] or format(n, "b").

Edge Cases

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.

Width

Minimal vs padded

Some tasks expect 00001111 instead of 1111.

Powers of two

8, 16, 64

One leading 1 and the rest zeros — good reverse checks.

One

n == 1

Smallest positive case — return "1".

Inverse

Binary to decimal

Practice the reverse conversion for interview completeness.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Uniqueness. Every nonnegative integer has a unique binary form without leading zeros (except 0 itself).
  • Bit length. Positive n needs floor(log2 n) + 1 bits — that is n.bit_length() in Python.
  • Inverse. Binary-to-decimal sums place values or uses int(s, 2).
  • Other bases. Replace 2 with 8 or 16 for octal/hex with the same remainder pattern.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 0 → 0
  • 15 → 1111
  • 64 → 1000000

2. Match all three styles

  • Remainder, bit scan, format
  • Assert identical strings

3. Fixed width

  • Pad to 8 bits
  • 15 → 00001111

4. Round-trip

  • Convert to binary then back
  • Use int(bits, 2)

Notes

  • Use remainder and division by 2 to build bits.
  • Always handle n == 0 separately.
  • Bit scan gives a neat MSB-to-LSB alternative.
  • State O(log n) time for positive n in bit-length terms.

Quick Takeaway: collect n % 2 remainders, reverse them (or scan from the MSB), and special-case zero.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Remainder + reverseO(log n)O(log n)
Bit scan using bit_lengthO(log n)O(log n)
Built-in format(n, "b")O(log n)O(log n) (output)

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

Wrap Up

🎉 Conclusion

Decimal-to-binary conversion is a clean remainder exercise: divide by 2, collect bits LSB-first, reverse for MSB-first output, and handle zero. Bit scan and format are strong follow-ups once the theory is clear.

Practice the three examples above, then continue to decimal-to-octal for the same pattern with base 8.

Always special-case 0, remember the first remainder is the LSB, and clarify minimal vs padded width.

💡 Best Practices

✅ Do

  • Handle n == 0 first
  • Explain LSB-first remainders
  • Reverse (or bit-scan) for MSB output
  • Test 0, 15, and 64
  • Mention format/bin as a shortcut

❌ Don’t

  • Forget the reverse step
  • Return empty string for 0
  • Leave negatives undefined
  • Assume padding when not asked
  • Ship bin(n) with the 0b prefix by accident

Key Takeaways

Knowledge Unlocked

Five things to remember about decimal to binary

Convert base 10 the interview-friendly way.

5
Core concepts
02

Order

LSB first

Math
0 03

Zero

Return "0"

Guard
> 04

Alt

Bit scan / format

Code
O 05

Complexity

O(log n)

Analysis

❓ Frequently Asked Questions

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.
Yes. bin(n)[2:] or format(n, 'b') are idiomatic for nonnegative integers after you understand the algorithm.
Binary to decimal — parse a 0/1 string with place values or int(bits, 2).

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.

Continue to Decimal to Octal

Learn how to convert decimal integers to octal with the same remainder pattern.

Decimal to octal tutorial →

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.

9 people found this page helpful