Decimal to Binary Conversion program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • realin
    Contributor
    • Feb 2007
    • 254

    Decimal to Binary Conversion program

    hi guys

    i am trying to make a program to convert decimal number into binary .. i am able to do that, but the number comes inverted.. like 1101 comes like 1011

    now how do i swap it off..

    here is teh code

    Code:
    import java.io.DataInputStream;
    class dec2b{
    
    public static void main(String a[]){
    
    	DataInputStream inp=new DataInputStream(System.in);
    	int nNum=0,nTemp=0,nSum=0,nBin=0,i=0;
    	
    	
    	System.out.println("Enter a Number to Convert into Binary");
    	
    	try{nNum=Integer.parseInt(inp.readLine());}
    	catch(Exception e){}
    	
    	while(nNum!=0)
    	{
    		
    		nTemp=nNum;
    		
    		if(nTemp%2==1)
    		nBin=1;
    		if(nTemp%2==0)
    		nBin=0;
    		
    		nSum=nSum*10+nBin;
    		nNum=nNum/2;
    		
    	}
    	System.out.println(nSum);
    }}
    please help me
    thanks
    Last edited by realin; Sep 7 '07, 03:37 PM. Reason: Email Notification
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by realin
    hi guys

    i am trying to make a program to convert decimal number into binary .. i am able to do that, but the number comes inverted.. like 1101 comes like 1011

    now how do i swap it off..
    You don't; you should read the API documentation for the Integer class. It's all there.

    kind regards,

    Jos

    Comment

    • realin
      Contributor
      • Feb 2007
      • 254

      #3
      Originally posted by JosAH
      You don't; you should read the API documentation for the Integer class. It's all there.

      kind regards,

      Jos
      hi jos,

      I know there is a straight function integer(11,2) .. but i wanna make it thru logic..

      cause that is my assignment.. thanks :)
      Last edited by realin; Sep 7 '07, 04:12 PM. Reason: Email Notification

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by realin
        hi jos,

        I know there is a straight function integer(11,2) .. but i wanna make it thru logic..

        cause that is my assignment.. thanks :)
        Recursion is your friend then (it avoids reversing the entire thing at the end).

        Suppose you have a number 'n' less than 2: the result will be "0" or "1" then; otherwise
        the result will be the binary string representation of the number n/2 appended with
        the binary string representation of n%2. You can even avoid the division and
        modulo by a bit of bit shifting (hint: >>> and <<).

        kind regards,

        Jos

        Comment

        • realin
          Contributor
          • Feb 2007
          • 254

          #5
          Originally posted by JosAH
          Recursion is your friend then (it avoids reversing the entire thing at the end).

          Suppose you have a number 'n' less than 2: the result will be "0" or "1" then; otherwise
          the result will be the binary string representation of the number n/2 appended with
          the binary string representation of n%2. You can even avoid the division and
          modulo by a bit of bit shifting (hint: >>> and <<).

          kind regards,

          Jos

          thanks seems interesting.. will try :)

          thanks thanks a lot

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Originally posted by realin
            hi jos,

            I know there is a straight function integer(11,2) .. but i wanna make it thru logic..

            cause that is my assignment.. thanks :)
            Use BufferedReader or Scanner instead of DataInputStream for reading input.
            To reverse an integer's digits, just make it a String, pass it to a StringBuilder and call the reverse method on it.

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #7
              Originally posted by JosAH
              Recursion is your friend then (it avoids reversing the entire thing at the end).

              Suppose you have a number 'n' less than 2: the result will be "0" or "1" then; otherwise
              the result will be the binary string representation of the number n/2 appended with
              the binary string representation of n%2. You can even avoid the division and
              modulo by a bit of bit shifting (hint: >>> and <<).

              kind regards,

              Jos
              There you go again ...

              Comment

              • fern7teensexy08
                New Member
                • Aug 2008
                • 1

                #8
                hello..can you tell me how to loop the decimal to binary conversion?

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by fern7teensexy08
                  hello..can you tell me how to loop the decimal to binary conversion?
                  What do you mean by "how to loop"? For all the rest: read this thread.

                  kind regards,

                  Jos

                  Comment

                  • jesz143
                    New Member
                    • Jan 2010
                    • 1

                    #10
                    this works fine

                    Code:
                    /*
                     * To change this template, choose Tools | Templates
                     * and open the template in the editor.
                     */
                    
                    package decimalbinary;
                    import javax.swing.*;
                    /**
                     *
                     * @author Admin
                     */
                    public class Main {
                    
                        /**
                         * @param args the command line arguments
                         */
                        public static void main(String[] args) {
                            // TODO code application logic here
                    
                            int x,i,q,z,temp=0;
                            q=0; z=0;
                           String a="";
                    x =Integer.parseInt(JOptionPane.showInputDialog("Please enter your number"));
                    
                        while (x!=0)
                        {temp=x;
                        x=temp/2;
                         q=temp%2;
                         a=q+a;
                    
                        }
                        String msg="Output is "+a;
                        JOptionPane.showMessageDialog(null, msg);
                        }
                    
                    }

                    Comment

                    • pbrockway2
                      Recognized Expert New Member
                      • Nov 2007
                      • 151

                      #11
                      Originally posted by jesz143
                      a=q+a;
                      Accumulating the digits in a StringBuilder and then reversing it at the end (as suggested by r\d*x) would remove the need for all these string concatenations.

                      Is there a reason why this thread was woken from its well deserved rest?

                      Comment

                      • power885
                        New Member
                        • Apr 2010
                        • 2

                        #12
                        Code:
                        class Binary
                        {
                            public static void main(String args[])
                            {
                        	int result=0;
                        	int val=48,nbin=0,k=0;
                        	while(val!=0)
                        	    {
                        		
                        	        nbin=(val%2==0)?0:1;
                                        result=nbin*(int)Math.pow(10,k)+result;
                                        val/=2; 
                        		++k;  
                        
                        	    }
                        	System.out.println(result);
                            }
                        }
                        I hope this may work for you

                        Comment

                        • power885
                          New Member
                          • Apr 2010
                          • 2

                          #13
                          Originally posted by JosAH
                          What do you mean by "how to loop"? For all the rest: read this thread.

                          kind regards,

                          Jos
                          Hello JosAH,
                          I posted my solution for decimal to binary conversion.Sinc e am newbie I need a suggestion to modify my solution

                          Comment

                          • jkmyoung
                            Recognized Expert Top Contributor
                            • Mar 2006
                            • 2057

                            #14
                            pbrockway2: I like your solution. No need for recursion!
                            Modifying the original code a little:
                            Code:
                            StringBuffer sb = new StringBuffer();
                              while(nNum!=0)  // code changes nNum
                                { 
                                    if(nNum%2==1) 
                                      sb.append(1); 
                                    else //        if(nNum%2==0) 
                                      sb.append(0);
                                    nNum >>= 1;  // same as nNum /= 2; 
                                }
                            sb.reverse();

                            Comment

                            • lokanath60
                              New Member
                              • May 2013
                              • 6

                              #15
                              Decimal to Binary Java Source code

                              This is the Program Which will convert a Decimal no to Binary fie ..


                              Code:
                              class Binary{
                              	public static void main(String[] args){
                              		int no=150;       //Input the No here
                              		int i=0;            
                              		int size=no/2;     //the no of 0 and 1 is no/2 approximetly;
                              		int a[]=new int[++size];    //creating an array of that size
                              		while(no>0){
                              				
                              			a[i++]=(no%2==0)?0:1;
                              		no /=2;
                              		}
                              		
                              		for(int j=i-1;j>=0;j--){
                              			
                              			System.out.print(a[j]);
                              
                              		}
                              		
                              	}
                              }

                              Comment

                              Working...