Decimal To Binary Conversion in Java

Discussion in 'Programming' started by mindblaster, Nov 26, 2009.

  1. #1
    Here's My Coding to Convert the Decimal number into Binary for newbie in Java. :cool:

    
    /**
     * @(#)Decimal To Binary.java
     *
     *
     * @author: Abdul Basit Ansari
     * @version 1.00 2009/11/26
     */
    
    import javax.swing.*;
    
    class DecimalToBinary
    {
    	public static void main (String[] args)
    		 {
    			DecToBin DtoB = new DecToBin();
    			DtoB.GetNumber();
    			DtoB.Convert();
    		 }	
    }
    
    class DecToBin
    {
    	int Decimal;  
    	
    	void GetNumber()
    	{
    		String D;
    		D = JOptionPane.showInputDialog(null,"Enter Decimal Number:");
    		Decimal = Integer.parseInt(D);
    		//JOptionPane.showMessageDialog(null,Decimal);
    	}
    	void Convert()
    	{
    		int[] A = new int[100];
    		int i=0;
    		
    		System.out.println("Decimal:" + Decimal);
    		while(Decimal!=1)
    		{
    			A[i] = Decimal % 2;
    			Decimal = Decimal / 2;
    			i++;
    		}
    		A[i]=1;
    
    		System.out.println("Binary:");				
    		for(int b=i; b>=0; b--)
    		{
    		 //JOptionPane.showMessageDialog(null,Binary);
    		 System.out.print(A[b]);
    		}
    	
    		
    		
    	}
    }
    
    
    Code (markup):

     
    mindblaster, Nov 26, 2009 IP
  2. mindblaster

    mindblaster Peon

    Messages:
    77
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    give me your suggestion to improve this code.

    thanks.
     
    mindblaster, Nov 26, 2009 IP
  3. jmpf

    jmpf Peon

    Messages:
    48
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'd change your class and everything to 'integer to binary' as it doesn't support decimals.
     
    jmpf, Nov 27, 2009 IP
  4. NeoCambell

    NeoCambell Peon

    Messages:
    456
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #4
    NeoCambell, Nov 28, 2009 IP
  5. mindblaster

    mindblaster Peon

    Messages:
    77
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    i know these methods, but i show the logic that how to do this without using builtin function.
    this logic also works on c++, vb, php etc
     
    mindblaster, Dec 2, 2009 IP
  6. NeoCambell

    NeoCambell Peon

    Messages:
    456
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #6
    ohhh...I though you are looking for a method.

    BTW: You may avoid using modulo operator and use bitwise operators like SHIFT, AND, etc...
    Example:
    values & 1 = 1, if last lsb is 1, i.e. odd number
    values & 1 = 0, if last lsb is 0, i.e. even number

    (value >> 1) = (value / 2)
    (value << 1) = (value * 2)

    You may now give a try to write a super efficient decimal to binary converter using these tips.
     
    NeoCambell, Dec 2, 2009 IP