Conversion programs in java
Question
Conversion programs in java. Convert the given binary number to decimal and decimal numbers to binary in an efficient way.
Program
[code lang=”java”]
import java.util.Scanner;
public class Binary {
public static void main(String ara[])
{
Scanner s=new Scanner(System.in);
int x = 5;
System.out.println("Enter a binary number:");
String n=s.nextLine();
System.out.println("Decimal of given binary: Integer.parseInt(n,2));// binary to decimal
System.out.println("Binary of 5: "+ Integer.toBinaryString(x)); // decimal to binary
}
}
[/code]
Explanation
- We are converting decimal to binary and binary to a decimal using java.
- Interegr.parseInt(String str) is the most commonly used method to convert String to int.
- The String is a decimal format representation.
- Internally, it invokes method Interegr.parseInt(String str, int radix) with radix value as 10.
- By passing radix value as 2, we can convert Binary int representation String to int.
- The same method can be applied for hexadecimal and octal with radix as 16,8 respectively.
You might also like…
Conversion program from number to words
Conversion program from decimal to binary