Convert a number to binary in Java
This post will discuss how to convert a number to binary in Java.
1. Using Built-in methods
The standard solution to convert a number to binary in Java is to use the Integer.toBinaryString() method, which returns the binary representation of the specified integer in string format.
|
1 2 3 4 5 6 7 8 9 10 11 |
class Main { public static void main(String[] args) { int n = 75; String binary = Integer.toBinaryString(n); System.out.println(binary); } } |
Output:
1001011
Similarly, you can convert a long using the Long.toBinaryString() method.
|
1 2 3 4 5 6 7 8 9 10 |
class Main { public static void main(String[] args) { long n = 75; String binary = Long.toBinaryString(n); System.out.println(binary); } } |
Output:
1001011
Alternatively, you can use the toString(i, r) method, which returns the string representation i in the radix r. However, this doesn’t work as intended for negative numbers.
|
1 2 3 4 5 6 7 8 9 10 |
class Main { public static void main(String[] args) { int n = 75; String binary = Integer.toString(n, 2); System.out.println(binary); } } |
Output:
1001011
If you need binary representation of the integer to be left-padded with zeros, you can use any of the methods discussed in this post:
2. Naive Solution
We can even write a custom routine to convert a number in binary format, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { public static String toBinary(int n, int length) { StringBuilder binary = new StringBuilder(); for (long i = (1L << length - 1); i > 0; i = i / 2) { binary.append((n & i) != 0 ? "1" : "0"); } return binary.toString(); } public static void main(String[] args) { int n = 75; int length = 32; String binary = toBinary(n, length); System.out.println(binary); } } |
Output:
00000000000000000000000001001011
Here’s a recursive version of the above code:
|
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 n) { if (n == 0) { return ""; } return toBinary(n / 2) + (n % 2); } public static void main(String[] args) { int n = 75; int length = 32; String binary = String.format("%0" + length + "d", Integer.valueOf(toBinary(n))); System.out.println(binary); } } |
Output:
00000000000000000000000001001011
That’s all about converting a number to binary 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 :)