Software & Finance





Java - Binary to Decimal





Here to the Java Source on to convert a binary number to a decimal number.

 

Source Code


import java.io.*;

 

 

class Binary2Decimal {

 

 

      static public long ConvertDecimal2Binary(long dec)

      {

            long bin = 0, pos = 1;

            while (dec > 0)

            {

                  bin = bin + (dec % 2) * pos;

                  dec = dec / 2;

                  pos *= 10;

            }

            return bin;

      }

 

 

      static public long ConvertBinary2Decimal(long bin)

      {

            long dec = 0, pos = 0;

            long factor = 1;

 

            while (bin > 0)

            {

                  if ((bin % 10) == 1)

                  {

                        dec += factor;

                  }

                  bin /= 10;

                  pos++;

                  factor = factor * 2;

            }

            return dec;

      }

 

 

 

 

    public static void main(String[] args) {

 

            String inpstring = "";

            InputStreamReader input = new InputStreamReader(System.in);

            BufferedReader reader = new BufferedReader(input);

 

            try

            {

                  System.out.print("Enter a Number for Binary to Decimal Conversion: ");

                  inpstring = reader.readLine();

 

                  long number = Long.parseLong(inpstring);

 

                  long binary = ConvertBinary2Decimal(number);

 

                  System.out.println("The decimal number is: " + binary);

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

    }

}

Output


C:\Java\Samples>javac Binary2Decimal.java

 

C:\Java\Samples>java Binary2Decimal

Enter a Number for Binary to Decimal Conversion: 1010

The decimal number is: 10