Given a Decimal value the task is to convert it to Binary value.
To convert Decimal value to Binary value we divide the number by 2 and take the remainder as the Binary bit. Then the quotient obtained is again divided by 2 and the remainder is taken as next Binary bit. This process is repeated until the number becomes 0.
Example 1: Consider a Decimal value 57.
| Division by 2 | Quotient | Remainder (Binary Bit) |
| 57/2 | 28 | 1 |
| 28/2 | 14 | 0 |
| 14/2 | 7 | 0 |
| 7/2 | 3 | 1 |
| 3/2 | 1 | 1 |
| 1/2 | 0 | 1 |
Now if we read the Binary bits of the adjacent table from bottom to top we will obtain the Binary equivalent of 57 that is 111001.
Java
import java.util.*;
public class DecimalBinary
{
public static void main(String args[])
{
int r=0,dec=0;
String bin="";
Scanner sc=new Scanner(System.in);
System.out.print("Decimal Value: ");
dec=sc.nextInt();
while(dec>0)
{
r=dec%2;
bin=r+bin;
dec=dec/2;
}
System.out.println("Binary Value: "+bin);
}
}Java