Java Program to Convert Decimal to Binary

In this example, we are giving a program to convert decimal number to a binary number.


To convert decimal to binary:

  1. # To convert decimal number to a binary number
  2. public class DecimalBinary {
  3. public static void main(String[] args) {
  4. long num = 19;
  5. long binary = convertDecimalToBinary(num);
  6. System.out.printf("%d in decimal = %d in binary", num, binary);
  7. }
  8. public static long convertDecimalToBinary(int n) {
  9. long binaryNumber = 0;
  10. int remainder, i = 1, step = 1;
  11. while (n != 0) {
  12. remainder = n % 2;
  13. System.out.printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
  14. n /= 2;
  15. binaryNumber += remainder * i;
  16. i *= 10;
  17. }
  18. return binaryNumber;
  19. }
  20. }

Output:

Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary