Software & Finance





Java - Decimal to Binary





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

 

Source Code


import java.io.*;

 

 

class Decimal2Binary {

 

 

      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 Decimal to Binary Conversion: ");

                  inpstring = reader.readLine();

 

                  long number = Long.parseLong(inpstring);

 

                  long binary = ConvertDecimal2Binary(number);

 

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

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

    }

}

 

Output


C:\Java\Samples>javac Decimal2Binary.java

 

C:\Java\Samples>java Decimal2Binary

Enter a Number for Decimal to Binary Conversion: 12

The binary number is: 1100