- Power
23
Convert Decimal to Binary in Java
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 withSystem.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.
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.
1515 = 2·7 + 1, 7 = 2·3 + 1, 3 = 2·1 + 1, 1 = 2·0 + 1 → bits from LSB up: 1 1 1 1 → 1111.
Intuition
- 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.
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
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 orderDivide 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).
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.
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.
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
🔄 Input / output examples
Example 1 uses 15 and 0; Example 2 shows 15 and 64.
| Decimal | Binary (minimal) |
|---|---|
0 | 0 |
1 | 1 |
15 | 1111 |
64 | 1000000 |
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.
n == 0
Must print 0; the naive remainder loop alone prints an empty line.
Fixed 8 vs minimal
Hardware often wants padded width (00001111); interview questions should state padding rules.
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.
Binary to decimal
See the paired Java tutorial for Horner / digit peel when the input is a bit string.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Remainder + array | O(log n) bits | O(log n) digits stored |
| 32-bit mask-style scan | O(32) = O(1) | O(1) |
MSB via numberOfLeadingZeros | O(1) | O(1) |
log is base 2 in the bit-length sense for nonnegative n.
Summary
- Idea: collect
n % 2while halvingn; 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.
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.
8 people found this page helpful
