Convert Decimal to Binary in Java
Problem
Binary is base 2: every digit is a bit worth a power of two, so 45 is written 101101 because 32 + 8 + 4 + 1 = 45.
Given a non-negative integer, print its binary representation.
Java Program
public class DecimalToBinary {
public static void main(String[] args) {
int number = 45;
if (number == 0) {
System.out.println("Binary of 0: 0");
return;
}
StringBuilder binary = new StringBuilder();
int n = number;
while (n > 0) {
binary.append(n % 2); // remainder is the next bit, lowest bit first
n /= 2;
}
System.out.println("Binary of " + number + ": " + binary.reverse()); // bits were collected backwards
}
}Output
Core Logic
Dividing by 2 strips off the lowest bit each time, and the remainder of that division is exactly the bit that was removed.
- 1
n % 2gives the current lowest bit, 0 or 1, which is appended tobinary. - 2
n /= 2drops that bit, shifting the remaining bits down by one place. - 3The loop repeats until
nreaches 0, so every bit is collected. - 4The bits come out lowest first, so
binary.reverse()puts them in reading order; 0 is handled separately because the loop would never run for it.
101101.Key Point: This loop only handles non-negative values — negative numbers in Java are stored in two's complement, which the built-in method shows as a full 32-bit pattern.
Why: The number halves on every step, so the loop runs once per bit, and the builder stores one character per bit.
Key Concepts
Approach 2: Using Integer.toBinaryString()
public class DecimalToBinaryBuiltIn {
public static void main(String[] args) {
int number = 45;
System.out.println("Binary of " + number + ": " + Integer.toBinaryString(number));
System.out.println("Binary of -45: " + Integer.toBinaryString(-45)); // two's complement, all 32 bits
}
}
Output
Core Logic
The standard library already does this conversion, and it also handles negative numbers by showing their two's complement bit pattern.
- 1
Integer.toBinaryString(45)returns the string"101101"directly. - 2Leading zeros are left off, just like in the manual version.
- 3For
-45it returns all 32 bits of the two's complement form, which starts with a run of 1s.
-45 becomes 11111111111111111111111111010011 — the same bits Java uses to store it in memory.Key Point: Use the built-in in real code; write the loop in interviews, where the point is to show you understand how base conversion works.
Why: The method still produces one character per significant bit (up to 32 for an int).
Key Concepts
Interview Questions
How do you pad the binary string to 8 bits?
String.format("%8s", Integer.toBinaryString(n)).replace(' ', '0').
How do you convert a negative number to binary?
Integer.toBinaryString(-n) shows its 32-bit two's complement form. Integer.toString(n, 2) keeps a minus sign instead.