Binary to decimal java

Hey guys!! Welcome to flower brackets blog. Today you are here to learn binary to decimal java.

binary to decimal java

To convert binary number to decimal number 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 in java. 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

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


Related Posts