Example 1 — Show Small Numbers in Binary
Print several numbers next to their binary text, with and without the zero padding to 8 bits.
public class IntegerToBinaryDemo {
static String pad8(int n) {
return String.format("%8s", Integer.toBinaryString(n)).replace(' ', '0');
}
public static void main(String[] args) {
int[] numbers = {0, 5, 65, 200, 255, 1024};
for (int n : numbers) {
System.out.println(n + " -> " + Integer.toBinaryString(n) + " -> " + pad8(n));
}
}
} How It Works
- No leading zeros. 5 becomes
101and 1024 becomes a 1 followed by ten zeros. - Zero is one digit. The number 0 gives the single character
"0", not an empty string. - Padding is manual.
%8sright-aligns the text in 8 characters with spaces, andreplaceturns those spaces into zeros. - Longer than 8 bits. 1024 needs 11 bits, so padding to 8 changes nothing.

