问题
How can i convert a decimal into binary? Is there any built in method which i can use to convert decimal into binary?
回答1:
you can use this method Integer.toBinaryString() it's built-in in java
回答2:
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.
回答3:
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);
}
}
来源:https://stackoverflow.com/questions/25958857/how-to-convert-a-decimal-to-binary-using-built-in-method-from-library-in-java