1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
class DeciToBinary{ public static void main(String args[]){ int a[]=new int[20]; int toCon = Integer.parseInt(args[0]); int temp = toCon; for(int i=0;temp!=0;i++){ a[i] = temp%2; temp = temp/2; } // reverse the array for(int i=0;i<(a.length)/2;i++){ temp = a[i]; a[i] = a[a.length-i-1]; a[a.length-i-1] = temp; } // print the binary number int binary=0; for(int i=0;i<a.length;i++){ if(a[i] == 0) continue; else{ while(i<a.length){ // only print the binary System.out.print(a[i]); // save binary to a int variable binary*=10; binary+=a[i]; i++; } System.out.println(); System.out.println("In the Variable : " + binary); } } } } |
Discussion
Above is long and tedious way to convert decimal to binary. Other way is :
1 2 3 4 5 6 7 8 9 10 11 |
class DeciToBinary{ public static void main(String args[]){ int toCon = Integer.parseInt(args[0]); String Con = Integer.toBinaryString(toCon); System.out.println("Binary is : " + Con); } } |