Convert Decimal to Binary in PHP

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.

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

81000₂
5101₂

Live Preview

Nonnegative integers in JavaScript safe range.

Live result
Press "Show binary" to convert.

Algorithm (remainder method)

📜 Pseudocode

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)
1

Divide by two and reverse bits

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

php
<?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";
?>
2

Bit-scan from MSB to LSB

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

php
<?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

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

DecimalBinary (minimal)
00
11
151111
641000000

Edge cases and pitfalls

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 padded output like 00001111 instead of 1111.

⏱️ Time and space complexity

ApproachTimeExtra space
Remainder + reverseO(log n)O(log n)
Bit scanO(log n)O(1) output aside

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