468,296 Members | 1,303 Online

# How to Print Binary of a Decimal Number

Any one Write this Program in a Better Way ..

Expand|Select|Wrap|Line Numbers
1. /*******
2. *@Author Lokanath Behera
3. *@Mob-[removed]
4. *@Email-[removed]@gmail.com
5. *****/
6.
7. class Binary{
8.     public static void main(String[] args){
9.         int no=19999;
10.         int i=0;
11.         int size=no/2;
12.         int a[]=new int[++size];
13.         while(no>0){
14.
15.         if(no%2==0){
16.             a[i++]=0;
17.         }
18.         else{
19.             a[i++]=1;
20.
21.         }
22.         no /=2;
23.         }
24.
25.         for(int j=i-1;j>=0;j--){
26.
27.             System.out.print(a[j]);
28.
29.         }
30.     }
31. }
32.
May 5 '13 #1
4 2025
Nepomuk
3,112 Expert 2GB
Define better. For example, an elegant way would be to do it recursively.
Even keeping with the loop approach, the length of the array can be calculated more accurately with
Expand|Select|Wrap|Line Numbers
1. // The length will be the logarithm of no to base 2, plus 1
2. int size = Math.log(no) / Math.log(2) + 1;
There are also ways to calculate logarithms to the base 2 more efficiently, so you could use those if efficiency is relevant.
Does that cover it or is there a specific way in which you want it improved?
May 6 '13 #2
vijay6
158 100+
Hey lokanath60, there is no need of if-else statement inside the while loop.
May 6 '13 #3
Nepomuk
3,112 Expert 2GB
Good point, you could just use
Expand|Select|Wrap|Line Numbers
1. while(no > 0){
2.   a[i++] = no % 2;
3.   no /=2;
4. }
May 6 '13 #4
Sherin
77 64KB
Try This Code

Expand|Select|Wrap|Line Numbers
1. public class BinaryDecimal {
2.
3.     public static void main(String[] args) {
4.         long num = 110110111;
5.         int decimal = convertBinaryToDecimal(num);
6.         System.out.printf("%d in binary = %d in decimal", num, decimal);
7.     }
8.
9.     public static int convertBinaryToDecimal(long num)
10.     {
11.         int decimalNumber = 0, i = 0;
12.         long remainder;
13.         while (num != 0)
14.         {
15.             remainder = num % 10;
16.             num /= 10;
17.             decimalNumber += remainder * Math.pow(2, i);
18.             ++i;
19.         }
20.         return decimalNumber;
21.     }
22. }
Jan 30 '21 #5