Java convert binary to decimal

Let’s learn java convert binary to decimal.

java convert binary to decimal

Java convert binary to decimal

Simple example of converting binary to decimal in java is one of the common java program interview question.

Algorithm to convert given binary number to decimal number is first user enters binary number.

In the next step each digit of binary number is multiplied with power of 2. This multiplied number is added with output.

Here we are using java.lang.Math class ‘pow’ method where power starts from 0 to n – 1, here, n is total number of binary digits.

Now let’s learn java program to convert binary number to decimal number,

import java.util.Scanner;

public class BinaryToDecimalDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter binary number : ");
      int number = sc.nextInt();
      int decimal = 0, a = 0, remainder;
      while(number != 0)
      {
         remainder = number % 10;
         number /= 10;
         decimal += remainder * Math.pow(2, a);
         ++a;
      }
      System.out.println("Decimal number : " + decimal);
      sc.close();
   }
}


Output:

Please enter binary number : 1111
Decimal number : 15

In java binary to decimal conversion there are two ways, one is using Integer.parseInt() method and another using custom logic.

Also read – comments in java

Lets see binary to decimal java while loop (custom logic),

public class BinaryToDecimalExample 
{
   public int convertToBinary(int binary)
   { 
      int decimal = 0;
      int b = 0;
      while(true)
      {
         if(binary == 0)
         {
            break;
         }
         else 
         {
            int temp = binary % 10;
            decimal += temp * Math.pow(2, b);
            binary = binary / 10;
            b++;
         }
      }
      return decimal;
   }

   public static void main(String[] args) 
   {
      BinaryToDecimalExample btd = new BinaryToDecimalExample();
      System.out.println("To decimal : " + btd.convertToBinary(110111));
   }
}



Output :

To decimal : 55


inbuilt function

Here let’s see program for binary to decimal conversion using Integer.parseInt() method.

Integer.parseInt() method takes two arguments string and radix to which we have to convert the number.

Here’s inbuilt function to convert binary to decimal,

public static int parseInt(String s, int radix) throws NumberFormatException

import java.util.Scanner;

public class BinaryToDecimalDemo
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner( System.in);
      System.out.println("Please enter a binary number : ");
      String num = sc.nextLine();
      // binary to decimal conversion
      System.out.println("Result : " + Integer.parseInt(num, 2));
      sc.close();
   }
}



Output:

Please enter a binary number : 1000
Result : 8

Click here for program and vice versa.