- Famous interview java question on conversions .
- We can convert binary to decimal in two ways
1.Using Integer.parseInt() method
2.Using custom logic
1.Write a Java Program to convert binary to decimal number in java without using Integer.parseInt() method.
- import java.util.Scanner;
- public class DecimalFromBinary {
- /**
- *www.instanceofjava.com
- */
- public static void main(String[] args) {
- Scanner in = new Scanner( System.in );
- System.out.println("Enter a binary number: ");
- int binarynum =in.nextInt();
- int binary=binarynum;
- int decimal = 0;
- int power = 0;
- while(true){
- if(binary == 0){
- break;
- } else {
- int tmp = binary%10;
- decimal += tmp*Math.pow(2, power);
- binary = binary/10;
- power++;
- }
- }
- System.out.println("Binary="+binary+" Decimal="+decimal); ;
- }
- }
Output:
- Enter a binary number:
- 101
- Binary=101 Decimal=5
2.Write a Java Program to convert binary to decimal number in java using Integer.parseInt() method.
- import java.util.Scanner;
- public class ConvertBinaryToDecimal{
- /**
- *www.instanceofjava.com
- */
- public static void main(String[] args) {
- Scanner in = new Scanner( System.in );
- System.out.println("Enter a binary number: ");
- String binaryString =input.nextLine();
- System.out.println("Result: "+Integer.parseInt(binaryString,2));
- }
- }
Output:
- Enter a binary number:
- 001
- Result: 1
You Might like:
Java Example program convert Decimal to Binary
Bagikan
Java Example Program to convert binary to decimal
4/
5
Oleh
Kris Kimcil