The Java program simply converts a decimal number to binary. In computing, a decimal number is a number system having a base of 10 ( 0 to 9), whereas a binary number having a base of 2 ( 0 or 1).
There are 3 following ways to convert a Decimal to Binary in Java :
Program:
import java.util.Scanner; public class DecimalToBinary { public static void main(String[] args) { Scanner input = new Scanner(System.in); int decimal, tmpDecimal; int binary[] = new int[20]; int i = 0; System.out.print("Please enter a decimal number = "); decimal = input.nextInt(); tmpDecimal = decimal; // While decimal number isn't equal to zero, do while (tmpDecimal != 0) { binary[i] = tmpDecimal % 2; // storing remainder in array named binary // Storing quotient within decimal variable itself, so that it shrinks down to 0 tmpDecimal = tmpDecimal / 2; i = i + 1; } // Printing array having binary numbers in reverse order System.out.print("\n Decimal number = " + decimal + "\n Binary Number= "); while (i >= 0) { System.out.print(binary[i]); i = i - 1; } System.out.print("\n"); } }
Output:
Please enter a decimal number = 79 Decimal number = 79 Binary Number= 01001111
Explanation:
Program :
public class DecimalToBinary { public static void main(String[] args) { int decimalNum = 79; System.out.println(" Decimal to Binary Value : " + Integer.toBinaryString(decimalNum)); } }
Output:
Decimal to Binary Value : 1001111
Explanation:
In above code, we used toBinaryString() method that directly converted the given number into Binary.
We can also achieve this functionality using recursion. A recursion method is a method that repeatedly calls itself until it satisfies a condition.
Program:
import java.util.Scanner; public class DecimalToBinary { public static void main(String[] args) { Scanner input = new Scanner(System.in); int decimal; System.out.print("Please enter a decimal number = "); decimal = input.nextInt(); System.out.print("\n Decimal number = " + decimal + "\n Binary Number= "); getReverse(decimal, new int[20], 0); } static void getReverse(int decimal, int[] binary, int i) { if (decimal != 0) { binary[i] = decimal % 2; // storing remainder in array named binary // Storing quotient within decimal variable itself, so that it shrinks down to 0 decimal = decimal / 2; i = i + 1; getReverse(decimal, binary, i); } else { while (i >= 0) { System.out.print(binary[i]); i = i - 1; } } } }
Output:
Please enter a decimal number = 79 Decimal number = 79 Binary Number= 01001111
This post was last modified on August 13, 2022