How can i convert a decimal into binary? Is there any built in method which i can use to convert decimal into binary?
Asked
Active
Viewed 9,033 times
3 Answers
3
I assume you want the binary representation of an integer number. You could use Integer.toBinaryString(int)
-
System.out.println(Integer.toBinaryString(0));
System.out.println(Integer.toBinaryString(255));
System.out.println(Integer.toBinaryString(-1));
Output is (the expected)
0
11111111
11111111111111111111111111111111
If my assumption is incorrect and you want the hex representation you can always use Integer.toHexString(int)
System.out.println(Integer.toHexString(255));
Which will get
ff
Finally, there's Integer.toOctalString(int)
if you need that. And, to reverse these operations there is Integer.parseInt(String, int)
where the second argument is the radix.

Elliott Frisch
- 198,278
- 20
- 158
- 249
-
1This converts a binary integer, not a decimal number. – user207421 Jun 17 '17 at 10:28
1
The java.lang package provides the functionality to convert a decimal number into a binary number. The method toBinaryString() comes in handy for such purpose. Bellow is the code:
import java.lang.*;
import java.io.*;
public class DecimalToBinary{
public static void main(String args[]) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal value:");
String hex = bf.readLine();
int i = Integer.parseInt(hex);
String by = Integer.toBinaryString(i);
System.out.println("Binary: " + by);
}
}

user3250183
- 506
- 6
- 19