Author Topic: Java - Decimal to Binary Conversion  (Read 739 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Java - Decimal to Binary Conversion
« on: November 14, 2011, 03:24:35 pm »
Here to the Java Source on to convert a decimal number to a binary number.


Code:
//Source Code Listing


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();
            }
    }
}


 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1