Wednesday, 23 November 2016

Decimal to Binary number

Binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). In this program, we start with the given decimal number, and repeatedly divide it by 2 (whole number division where the result will be only the quotient, a whole number) and note down the remainder at every step till we obtain the quotient as 0. The remainders obtained in each step when concatenated together (the last remainder taken as the first digit of the binary number) give the binary form of the decimal number. For example, the binary form of decimal number 15 is 1111.



PROGRAM
class DecimalToBinary {

 public static void main(String[] args) {
  
  int num = Integer.parseInt(args[0]);
  String binary="";
  
  while (num > 0) {
   
   binary = (num % 2) + binary;
   num = num / 2;
  }
  
  System.out.println("Binary number is :: " + binary);
 }
}
OUTPUT 1
C:\>javac DecimalToBinary.java
C:\>java DecimalToBinary 15
Binary number is :: 1111
OUTPUT 2
C:\>javac DecimalToBinary.java
C:\>java DecimalToBinary 50
Binary number is :: 110010

No comments:

Post a Comment