How to Print Binary of a Decimal Number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lokanath60
    New Member
    • May 2013
    • 6

    How to Print Binary of a Decimal Number

    Any one Write this Program in a Better Way ..

    Code:
    /*******
    *@Author Lokanath Behera
    *@Mob-[removed]
    *@Email-[removed]@gmail.com
    *****/
    
    class Binary{
    	public static void main(String[] args){
    		int no=19999;
    		int i=0;
    		int size=no/2;
    		int a[]=new int[++size];
    		while(no>0){
    					
    		if(no%2==0){
    			a[i++]=0;
    		}
    		else{
    			a[i++]=1;
    			
    		}
    		no /=2;
    		}
    		
    		for(int j=i-1;j>=0;j--){
    			
    			System.out.print(a[j]);
    
    		}
    	}
    }
    Last edited by acoder; May 5 '13, 10:47 PM. Reason: Removed personal information
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    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
    Code:
    // The length will be the logarithm of no to base 2, plus 1
    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?

    Comment

    • vijay6
      New Member
      • Mar 2010
      • 158

      #3
      Hey lokanath60, there is no need of if-else statement inside the while loop.

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Good point, you could just use
        Code:
        while(no > 0){
          a[i++] = no % 2;
          no /=2;
        }

        Comment

        • Sherin
          New Member
          • Jan 2020
          • 77

          #5
          Try This Code

          Code:
          public class BinaryDecimal {
          
              public static void main(String[] args) {
                  long num = 110110111;
                  int decimal = convertBinaryToDecimal(num);
                  System.out.printf("%d in binary = %d in decimal", num, decimal);
              }
          
              public static int convertBinaryToDecimal(long num)
              {
                  int decimalNumber = 0, i = 0;
                  long remainder;
                  while (num != 0)
                  {
                      remainder = num % 10;
                      num /= 10;
                      decimalNumber += remainder * Math.pow(2, i);
                      ++i;
                  }
                  return decimalNumber;
              }
          }

          Comment

          Working...