- Power
2^3
Convert Decimal to Binary in Python
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.
Division algorithm
For n ≥ 0, repeatedly write n = 2q + r with r in {0,1}. The remainders form binary digits from right to left.
1515→7 r1, 7→3 r1, 3→1 r1, 1→0 r1 so binary is 1111.
Intuition
- Sum
4 + 1
Takeaway: each division step answers odd/even at the current scale.
Live Preview
Nonnegative integers in JavaScript safe range.
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
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) Divide by two and reverse bits
Classic approach: collect remainder bits, then reverse to print MSB-first.
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.
Bit-scan from MSB to LSB
No reversal buffer needed. Start at highest set bit and read downward.
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
🔄 Input / output examples
Use these values to verify both approaches.
| Decimal | Binary (minimal) |
|---|---|
0 | 0 |
1 | 1 |
15 | 1111 |
64 | 1000000 |
Edge cases and pitfalls
Handle zero explicitly and define behavior for negatives before coding.
n == 0
Return "0"; otherwise a plain while n > 0 loop returns empty output.
Policy choice
Choose absolute-value conversion or fixed-width two's complement and document it clearly.
Minimal vs padded
Some tasks expect 00001111 instead of 1111; padding rules matter.
Binary to decimal
Practice the reverse conversion too for interview completeness.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Remainder + reverse | O(log n) | O(log n) |
| Bit scan using bit_length | O(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 == 0separately. - Bit scan gives a neat MSB-to-LSB alternative.
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.
8 people found this page helpful
