This is my very first tutorial on this forum :lol:
Converting Decimal to Binary is quite simple. This is how we do it :
/**
* Converts Decimal To Binary
*
* @author Kushtrim
* @version 14.12.2011
*/
import javax.swing.*;
public class DecimalToBinary
{
public static void main(String[] args)
{
long d = new Long(JOptionPane.showInputDialog("Write the number in decimal form: ")).longValue();
String binary="";
for ( long decimal = d ; decimal > 0 ; decimal/=2 )
{
binary = decimal%2 + binary ;
}
JOptionPane.showMessageDialog(null,"Binary number:\n " + binary);
}
}
The logic behind this is really simple, u just got to know a little math.,
To convert a number from decimal form ( base-ten , u know the system we normally use), eg. 4, u divide it by 2, and you get a reminder 0 or 1 ( in our case 4:2=2, remainder 0) ... We repeat this process(loop) until we get the quotient 0 (the remainder of 1:2=0 will be 1).
Then we read it from bottom to top ( from the last remainder).
Our example:
4:2=2 remainder 0
2:2=1 remainder 0
1:2=0 remainder 1
Decimal 4 = Binary 100
Feel free to ask if you didn't understand it:)


Sign In
Create Account


Back to top









