Convert an integer to a binary string of a specific length in Java
This post will discuss how to convert an integer to a binary string of a specific length in Java. The solution should left-pad the binary string with leading zeros.
There are several ways to convert an integer to binary format in Java:
1. Using String.format() method
To get a binary string of a specific length with leading zeros, we can use the format() method of the String class as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { public static String toBinary(int x, int len) { if (len > 0) { return String.format("%" + len + "s", Integer.toBinaryString(x)).replaceAll(" ", "0"); } return null; } public static void main(String[] args) { System.out.println(toBinary(1000, 16)); } } |
Output:
0000001111101000
2. Custom routine
We can also write our own routine to convert an integer to a binary string of a specific length with leading zeros. This can be done using either a StringBuilder or a char array.
⮚ Using StringBuilder:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Main { public static String toBinary(int x, int len) { StringBuilder result = new StringBuilder(); for (int i = len - 1; i >= 0 ; i--) { int mask = 1 << i; result.append((x & mask) != 0 ? 1 : 0); } return result.toString(); } public static void main(String[] args) { System.out.println(toBinary(1000, 16)); } } |
Output:
0000001111101000
⮚ Using char array:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Main { public static String toBinary(int x, int len) { final char[] buff = new char[len]; for (int i = len - 1; i >= 0 ; i--) { int mask = 1 << i; buff[len - 1 - i] = (x & mask) != 0 ? '1' : '0'; } return new String(buff); } public static void main(String[] args) { System.out.println(toBinary(1000, 16)); } } |
Output:
0000001111101000
That’s all about converting an integer to a binary string of a specific length in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)