Explain Codes LogoExplain Codes Logo

Print an integer in binary format in Java

java
binary-conversion
java-built-in-functions
performance-optimization
Nikita BarsukovbyNikita Barsukov·Mar 3, 2025
TLDR

The quickest way to convert an integer to binary in Java is to use the Integer.toBinaryString() method.

String binary = Integer.toBinaryString(10); System.out.println(binary); // Prints "1010" and not a wishlist

When we need binary representation for larger numbers, Java has us covered. For long values, use Long.toBinaryString(long). For even larger numbers, BigInteger.toString(2) becomes our superhero.

Need your binary number padded with leading zeros? Trust the String.format() to do the heavy lifting:

String binaryStringWithLeadingZeros = String.format("%32s", Integer.toBinaryString(10)).replace(' ', '0'); System.out.println(binaryStringWithLeadingZeros); // Prints 32-digit string, finally something longer than my grocery list!

Detailed explanation of binary conversion

Master of all bases

Our friendly function Integer.toString(int, radix) is here to convert our integers to a base of our choosing:

String binary = Integer.toString(10, 2); // Binary is Base 2 String octal = Integer.toString(10, 8); // Octal is Base 8 String hex = Integer.toString(10, 16); // Hexadecimal is Base 16

Formatting binary output

To maintain a uniform binary string length, add leading zeros:

int number = 5; String formattedBinary = String.format("%8s", Integer.toBinaryString(number)).replaceAll(" ", "0"); System.out.println(formattedBinary); // Prints "00000101", now you can't say I have no class

Binary conversion for bytes and shorts

In the world of bytes and shorts, bitwise AND operations reign supreme:

byte b = 5; String binaryByte = Integer.toBinaryString(b & 0xFF); System.out.println(binaryByte); // Prints "101", finally a byte-size binary!

Leverage built-in functions

Why create a [binary] wheel when you don't have to? With Java's built-in methods, optimized and thoroughly tested, creating your own binary conversion method can be as pointless as a broken pencil.

Padding: not just for bras and resumes

Correct padding is crucial when displaying binary numbers. Fret not! Simply add leading zeros should the binary representation fall short of the expected length.

Efficiency at its best

Java's built-in functions aren't just about simplicity. Engineered for performance, these native methods can beat the pants off any manual binary conversion you can come up with.