/* Mock test Lab on 17-09-2008 Wednesday * Write a JAVA program to convert a number given in decimal number representation to * its equivalent binary number representation and print the binary value. For example, if * the input is 25, then the output should be 11001 (which is the binary representation of * 2510 ). Similarly, if the input is −11 then the output should be −1011 (which is the binary * representation of −1110 ). Your program has to work for all values of integer n whose binary * representation has 10 digits only. You must take the input as command-line argument. */ public class DecimalToBinary { public static void main(String[] args) { //Checking for the number of command line arguments if(args.length !=1 ) { System.out.println("Please supply a integer arguement with the program..."); return; } int decimalNumber , binaryEquivalent; //Parsing the number given in command line try { decimalNumber = Integer.parseInt(args[0]); } catch(NumberFormatException ex) { System.out.println("The supplied arguemt cannot be parsed as integer..."); return; } //Making sure that the command line argument passed is an integer else terminate with message //Decimal number >= 1024 will require more than 10 bits in binary equivalent so are the decimal numbers <= -1024 if(decimalNumber >= 1024 || decimalNumber <= -1024) { System.out.println("Binary representation of " + decimalNumber + " will take more than 10 bits..."); return; } //If decimalNumber is positive the we pass the number directly to returnBinaryEquivalent if(decimalNumber >= 0) { binaryEquivalent = returnBinaryEquivalent(decimalNumber); System.out.println(binaryEquivalent); } //else we pass the absolute value and print the binary equivalent of the absolute value appended by a negation else { binaryEquivalent = returnBinaryEquivalent(-decimalNumber); System.out.println("-"+binaryEquivalent); } } //Function returning the binary equivalent of +ve decimal integers public static int returnBinaryEquivalent(int decimalNumber) { int binaryNumber = 0, counter = 1; //Every time we get a decimalNumber%2 we append it as MSB of the binaryNumber. We use a counter for it to track the position of MSB while(decimalNumber != 0) { binaryNumber = binaryNumber + (decimalNumber%2) * counter; counter *= 10; decimalNumber /= 2; } return binaryNumber; } }