## Binary and decimal conversion in java

*Question*

Convert the given binary number to decimal and decimal number to binary in an efficient way.

*Program*

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 } }

*Explanation*

- 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.