Convert Decimal to Binary in PHP
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.
Prerequisites
Basic loops, modulo, integer division, and strings in PHP.
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.
Division algorithm
For n ≥ 0, repeatedly write n = 2q + r with r in {0,1}. The remainders form binary digits from right to left.
Intuition
Live Preview
Nonnegative integers in JavaScript safe range.
Algorithm (remainder method)
📜 Pseudocode
function decimalToBinary(n):
if n == 0: return "0"
bits = []
while n > 0:
bits.append(n % 2)
n = floor(n / 2)
reverse(bits)
return join(bits)Divide by two and reverse bits
Classic approach: collect remainder bits, then reverse to print MSB-first.
<?php
function decimalToBinary(int $n): string
{
if ($n === 0) return "0";
$bits = [];
while ($n > 0) {
$bits[] = (string)($n % 2);
$n = intdiv($n, 2);
}
return implode('', array_reverse($bits));
}
echo decimalToBinary(15) . "\n";
echo decimalToBinary(0) . "\n";
?>Bit-scan from MSB to LSB
No reversal buffer needed. Start at highest set bit and read downward.
<?php
function toBinaryBitScan(int $n): string
{
if ($n === 0) return "0";
$out = '';
$started = false;
for ($b = 31; $b >= 0; $b--) {
$bit = ($n >> $b) & 1;
if ($bit || $started) {
$out .= $bit ? '1' : '0';
$started = true;
}
}
return $out;
}
echo toBinaryBitScan(15) . "\n";
echo toBinaryBitScan(64) . "\n";
?>Optimization
Built-in fast path. For nonnegative integers, decbin($n) is concise and reliable.
Fixed width. Use str_pad(decbin($n), 8, '0', STR_PAD_LEFT) when padding is required.
Interview: explain remainder logic first, then mention bit-scan or built-in.
❓ FAQ
🔄 Input / output examples
| Decimal | Binary (minimal) |
|---|---|
0 | 0 |
1 | 1 |
15 | 1111 |
64 | 1000000 |
Edge cases and pitfalls
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 padded output like 00001111 instead of 1111.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Remainder + reverse | O(log n) | O(log n) |
| Bit scan | O(log n) | O(1) output aside |
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
