Java convert binary to decimal

Let’s learn java convert binary to decimal.

java convert binary to decimal

Java convert binary to decimal

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

// binary to decimal java while loop
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 program for binary to decimal conversion 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 – methods 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();
      // binary to decimal conversion
      System.out.println("Result : " + Integer.parseInt(num, 2));
      sc.close();
   }
}



Output:

Please enter a binary number : 1000

Result : 8