Java convert binary to decimal

Today you are here to learn java convert binary to decimal.

java convert binary to decimal

Java convert binary to decimal

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

Also read – convert int to binary java

Lets dig into latter, that is, using 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


Using parseInt() method

Here let’s see Integer.parseInt() method to convert binary number to decimal number. This method takes two arguments. One is string and another is radix to which we have to convert the number.

Also read – octal to decimal in java

Here’s the signature of parseInt() method,

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();
      System.out.println("Result : " + Integer.parseInt(num, 2));
      sc.close();
   }
}

Output:

Please enter a binary number : 1000

Result : 8