Convert Decimal to Binary in Java

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

What you’ll learn

  • How division by two and remainders yield binary digits from right to left.
  • Why you must handle zero and why the first implementation prints the array backwards.
  • An MSB-first bit walk using shifts, a live preview, and links to the inverse tutorial.

Overview

Binary uses powers of two. To express a nonnegative decimal integer in base two, repeatedly divide by 2 and record remainders 0 or 1; read those bits from last generated to first for MSB-first output.

Two programs

Remainder stack in an array (classic), then bit-mask style MSB scan in Java.

Live preview

Nonnegative safe integers; mirrors Integer.toBinaryString(n) as a quick check.

Inverse

Pair with binary to decimal in Java for a full interview story.

Prerequisites

Integer division and modulo, arrays, for loops, and optional bitwise operators in Java.

  • public static void main(String[] args), integer division, and printing with System.out.println.
  • Optional: bitwise AND (&) and shifts (<<, >>>) for the MSB scan.

Decimal to binary

Each binary digit (bit) is a coefficient on a power of two. Converting a nonnegative integer n collects those bits by peeling parity: n % 2 is the least significant bit, then n /= 2 shifts right in value.

Example: 15 = 8 + 4 + 2 + 1 = 1·23 + 1·22 + 1·21 + 1·20, written 11112.

Decimal base 10
Binary base 2
Example 15 → 1111

Division algorithm

For n ≥ 0, define b0 = n mod 2, n1 = ⌊n/2⌋, then b1 = n1 mod 2, and so on until the quotient is 0. The sequence bk…b0 (reversed index) is the binary expansion of n.

15

15 = 2·7 + 1, 7 = 2·3 + 1, 3 = 2·1 + 1, 1 = 2·0 + 1 → bits from LSB up: 1 1 1 11111.

Intuition

8 1000₂
Power
23
5 101₂
Sum
4 + 1

Takeaway: each division step answers “odd or even?” at the current scale—that is the next bit.

Live preview

Nonnegative integers in the JavaScript safe range. Uses Number#toString(2) for a quick binary string.

Negative values are rejected here; signed two's complement is a separate convention.

Live result
Press “Show binary” to convert.

Algorithm (remainder method)

Goal: print bits of nonnegative n in MSB-first order.

Special case n == 0

Print a single 0 and stop (the pure while (n > 0) loop prints nothing otherwise).

Collect bits

While n > 0: push n % 2, then n /= 2.

Print reversed

Emit stored bits from last pushed down to first.

📜 Pseudocode

Pseudocode
function printBinaryFromDecimal(n):  // n ≥ 0
    if n = 0:
        output "0"; return
    bits ← empty list
    while n > 0:
        append (n mod 2) to bits
        n ← floor(n / 2)
    print bits in reverse order
1

Divide by two with reverse print

Same structure as the reference, with an explicit zero branch. Uses a modest array for bits (enough for typical int magnitudes on this page).

java
public class Main {

    static String decimalToBinary(int decimalNumber) {
        if (decimalNumber == 0) {
            return "0";
        }

        int n = decimalNumber;
        int[] bits = new int[32];
        int i = 0;

        while (n > 0) {
            bits[i] = n % 2;
            n /= 2;
            i++;
        }

        StringBuilder sb = new StringBuilder(i);
        for (int j = i - 1; j >= 0; j--) {
            sb.append(bits[j]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        int decimalNumber = 15;

        System.out.println("Binary equivalent of " + decimalNumber + ": " + decimalToBinary(decimalNumber));
        System.out.println("Binary equivalent of 0: " + decimalToBinary(0));
    }
}

Explanation

The first remainder is the least significant bit. Storing bits into an array and then walking it backwards prints the binary string from MSB to LSB.

if (decimalNumber == 0)

Zero case. Avoids an empty output when the loop never runs.

2

MSB-to-LSB with a bit-mask style loop

No reversal buffer: scan from bit 31 down to 0, skip leading zeros unless the value is 0. This mimics a 32-bit mask scan using Java shifts.

java
public class Main {

    static String toBinaryMsb(int n) {
        if (n == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder(32);
        boolean started = false;

        for (int b = 31; b >= 0; b--) {
            int bit = (n >>> b) & 1;
            if (bit == 1 || started) {
                sb.append(bit);
                started = true;
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println("15 as binary: " + toBinaryMsb(15));
        System.out.println("64 as binary: " + toBinaryMsb(64));
    }
}

Explanation

The unsigned right-shift n >>> b moves bit b into the least significant position; masking with & 1 extracts it as 0 or 1.

if (bit == 1 || started)

Skip leading zeros. The first 1 starts the printed prefix; zeros after that are meaningful bits.

Optimization

Use built-ins. For everyday Java code, Integer.toBinaryString(n) (and padding if needed) is the simplest path.

Find MSB once. You can find the index of the highest set bit with 31 - Integer.numberOfLeadingZeros(n) and start your loop there instead of always at 31.

Interview: mention n == 0, how you handle sign, and the inverse conversion.

❓ 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 walks MSB to LSB.
while (n > 0) never runs, so nothing is printed. Handle n == 0 as a special case that outputs a single 0.
It tests bits from a fixed high position down (for example 31 down to 0 for 32-bit int), skipping leading zeros except when the value is 0. No temporary array is required, and the output is MSB-first.
Java uses two's complement for signed ints. If you want the raw 32-bit pattern of an int, you can use Integer.toBinaryString(n) and pad, or mask with 0xFFFFFFFFL. If you only care about the magnitude, convert Math.abs(n) and keep track of the sign.
Either enough for your problem (e.g. 8 bits) or from the highest set bit down (variable width). For a full 32-bit view you can pad the result with leading zeros to length 32.
O(b) for b output bits: about log2(n) for positive n in the remainder method, or O(W) for a fixed width W in the mask-like scan.

🔄 Input / output examples

Example 1 uses 15 and 0; Example 2 shows 15 and 64.

DecimalBinary (minimal)
00
11
151111
641000000

Edge cases and pitfalls

Signed division with negative n does not implement “binary string of absolute value”; pick a clear rule for sign and stick with it.

Zero

n == 0

Must print 0; the naive remainder loop alone prints an empty line.

Width

Fixed 8 vs minimal

Hardware often wants padded width (00001111); interview questions should state padding rules.

Unsigned view

Negative ints

To inspect raw bits of an int, you can use Integer.toBinaryString(n) and pad to 32 bits; the high bit shows the sign in two's complement.

Inverse

Binary to decimal

See the paired Java tutorial for Horner / digit peel when the input is a bit string.

⏱️ Time and space complexity

ApproachTimeExtra space
Remainder + arrayO(log n) bitsO(log n) digits stored
32-bit mask-style scanO(32) = O(1)O(1)
MSB via numberOfLeadingZerosO(1)O(1)

log is base 2 in the bit-length sense for nonnegative n.

Summary

  • Idea: collect n % 2 while halving n; print bits in reverse, or scan bits MSB-down with shifts.
  • Code: always handle 0, and be explicit about how you represent negative values.
  • Pair: use the Java binary-to-decimal tutorial for the reverse direction.
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-mask style loop prints 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