Here's My Coding to Convert the Decimal number into Binary for newbie in Java. /** * @(#)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):
There is a built in method to get this done in java. Have a look at http://www.expertcore.org/viewtopic.php?f=11&t=879
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
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.