Java program to convert binary to decimal number

Java program to convert binary to decimal number

In this java program, we are going to learn how to automate converting binary numbers to decimal numbers.

Solution:
Binary number is 10111

10111 = (1 × 24) + (0 × 23) + (1 × 22) + (1 × 21) + (1 × 20)

= 16 + 0 + 4 + 2 +1
= 23
Decimal Number = 23

Java program to convert binary to decimal number using while loop.

In this java program, using while loop to convert binary to decimal numbers.

import java.io.*;
import java.util.*;

public class BinaryToDecimal {

    public static void main(String[] args) {
        int number;
        long decimalNumber = 0;
        int remainder, i = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter binary number: ");
        number = in.nextInt();
        while (number != 0)
        {
            remainder = number % 10;
            number /= 10;
            decimalNumber += remainder * Math.pow(2, i);
            ++i;
        }
        System.out.println("Decimal number: "+ decimalNumber);
    }

}





Output:

Enter binary number: 10111
Decimal number: 23

Java program to convert binary to decimal number using for loop.

In this java program, using for loop to convert binary to decimal numbers.

import java.io.*;
import java.util.*;

public class BinaryToDecimal {

    public static void main(String[] args) {
        int number;
        long decimalNumber = 0;
        int remainder, i = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter binary number: ");
        number = in.nextInt();
        for (;number != 0;++i)
        {
            remainder = number % 10;
            number /= 10;
            decimalNumber += remainder * Math.pow(2, i);
        }
        System.out.println("Decimal number: "+ decimalNumber);
    }

}

Output:

Enter binary number: 10111
Decimal number: 23

We can also make the java program with only for loop statement with no block statements,

import java.io.*;
import java.util.*;

public class BinaryToDecimal {

    public static void main(String[] args) {
        int number;
        long decimalNumber = 0;
        int remainder, i = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter binary number: ");
        number = in.nextInt();
        for (;number != 0;remainder = number % 10,number /= 10, decimalNumber += remainder * Math.pow(2, i),++i);

        System.out.println("Decimal number: "+ decimalNumber);
    }

}

Output:

Enter binary number: 10111
Decimal number: 23




Python installation

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^