To convert a number from the decimal system to the binary system, the toBinaryString()
method is used in Java. The Integer
class provides several methods, such as the conversion methods.
import java.util.Scanner;
public class ConvertToBinary {
public static void main(String[] args) {
int num;
Scanner s = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = s.nextInt();
s.close();
String binary = Integer.toBinaryString(num);
System.out.println("Binary value of number " + num + " is: " + binary);
}
}
Please enter a number: 13
Binary value of number 13 is: 1101