This post will discuss how to convert an integer to a 32-bit binary string in Java.

There are several ways to convert an integer to binary format in Java:

1. Using Integer.toBinaryString() method

A simple solution is to use the toBinaryString() method provided by the Integer wrapper class. It takes an integer to be converted to a string and return its string representation in binary format.

Note that the binary representation returned by toBinaryString() is not left-padded with zeros.

Download  Run Code

Output:

10011100010000
11111111111111111101100011110000

2. Using Apache Commons Lang

To pad the binary value with leading zeros to a specific length, we can use StringUtils class from Apache Commons Lang Library:

Download Code

Output:

00000000000000000010011100010000
11111111111111111101100011110000

3. Using String.format() method

Another alternative to left pad the binary representation of an integer with zeros is to use the format() method of the String class. It can be used as follow:

Download  Run Code

Output:

00000000000000000010011100010000
11111111111111111101100011110000

4. Custom routine

We can also write our own routine to display the leading zeros using a StringBuilder or a char array.

⮚ Using StringBuilder:

Download  Run Code

Output:

00000000000000000010011100010000
11111111111111111101100011110000

⮚ Using char array:

Download  Run Code

Output:

00000000000000000010011100010000
11111111111111111101100011110000

5. Using Integer.toString() method

Finally, the Integer class provides another built-in method, toString(), that returns a string representation of an integer in the specified radix. This doesn’t work with negative integers.

Download  Run Code

Output:

10011100010000

 
BigInteger has a similar method where we can specify the radix.

Download  Run Code

Output:

10011100010000

That’s all about converting an integer to binary in Java.

 
Also See:

Convert an integer to a binary string of a specific length in Java