Java convert binary to decimal

Let’s learn java convert binary to decimal.

Java convert binary to decimal

binary to decimal in java is one of the common interview question. In the below example first user enters binary number using nextLine() method of Scanner class.

java convert binary to decimal

This binary number is stored in String variable ‘strBinary’. Now this string variable is converted using Integer.parseInt() method (inbuilt function).

In the next step each binary digit is multiplied with power of 2a and added. Where ‘a’ is position of binary number from right side. Now let’s see program to convert binary to decimal using while loop.

// convert binary to decimal in java
import java.util.Scanner;
public class BinaryToDecimalDemo 
{
   public static void main(String[] args) 
   {
      int number, decimal = 0, a = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter binary number: ");
      String strBinary = sc.nextLine();
      number = Integer.parseInt(strBinary);
      while(number != 0){
         decimal += (number % 10) * Math.pow(2, a);
         number = number / 10;
         a++;
      }
      System.out.println("Decimal number: " + decimal);
      sc.close();
   }
}


Output:

Please enter binary number : 1111
Decimal number : 15


Let’s learn binary to decimal conversion in java 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 obj = new BinaryToDecimalExample();
      System.out.println("To decimal : " + obj.convertToBinary(110111));
   }
}


Output:

To decimal : 55


Binary to decimal java program using inbuilt function

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

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

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

Integer.parseInt() method returns the integer represented by the string argument in the specified radix.

This method parses the string argument as a signed integer in the radix specified by the second argument.

import java.util.*;
public class BinaryToDecimalDemo
{
   public static void main(String[] args)
   {
      String strBinary = "110111";
      int decimal = Integer.parseInt(strBinary, 2); 
      System.out.println(decimal);
   }
}


Output:

55


Also read – abstraction in java