Java Program to Convert Binary Number to Decimal and vice-versa

In this program, you’ll learn to convert binary number to a decimal number and vice-versa using functions in Java.

Example 1: Program to convert binary number to decimal

  1. public class BinaryDecimal {
  2. public static void main(String[] args) {
  3. long num = 110110111;
  4. int decimal = convertBinaryToDecimal(num);
  5. System.out.printf("%d in binary = %d in decimal", num, decimal);
  6. }
  7. public static int convertBinaryToDecimal(long num)
  8. {
  9. int decimalNumber = 0, i = 0;
  10. long remainder;
  11. while (num != 0)
  12. {
  13. remainder = num % 10;
  14. num /= 10;
  15. decimalNumber += remainder * Math.pow(2, i);
  16. ++i;
  17. }
  18. return decimalNumber;
  19. }
  20. }

When you run the program, the output will be:

110110111 in binary = 439 in decimal

 

Example 2: Program to convert decimal number to binary

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

When you run the program, the output will be:

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