Java Decimal to Binary

Converting a decimal number to binary in Java can be done in a couple of different ways: either by using a built-in Java function or by implementing a custom manual conversion. Let’s explore both approaches in detail.

Method 1: Using Integer.toBinaryString()

Java provides a convenient built-in method Integer.toBinaryString() that converts a decimal (base 10) integer into a binary (base 2) string.

Syntax:


String binaryString = Integer.toBinaryString(int decimalValue);

Example 1: Using Integer.toBinaryString() Method


public class DecimalToBinary {
    public static void main(String[] args) {
        int decimalValue = 43;  // example decimal number

        // Convert decimal to binary
        String binaryString = Integer.toBinaryString(decimalValue);

        // Output the result
        System.out.println("Decimal: " + decimalValue);
        System.out.println("Binary: " + binaryString);
    }
}

Output:

  • Decimal: 43
  • Binary: 101011

Explanation:

  • Integer.toBinaryString(decimalValue): Converts the decimal integer 43 to a binary string.
  • Decimal 43 is equivalent to binary 101011.

Method 2: Manual Conversion

If you want to manually convert a decimal number to binary, you can repeatedly divide the decimal number by 2, recording the remainders. The binary representation is constructed by reading the remainders from bottom to top.

Conversion Process:

  1. Divide the decimal number by 2.
  2. Record the remainder (either 0 or 1).
  3. Update the decimal number to the quotient of the division.
  4. Repeat steps 1-3 until the quotient is 0.
  5. The binary number is the sequence of remainders, read in reverse order (from last to first).

Example 2: Manual Conversion of Decimal to Binary


public class DecimalToBinary {
    public static void main(String[] args) {
        int decimalValue = 43;  // example decimal number
        String binaryString = "";

        // Convert decimal to binary manually
        while (decimalValue > 0) {
            int remainder = decimalValue % 2;  // Get remainder (either 0 or 1)
            binaryString = remainder + binaryString;  // Prepend remainder to the binary string
            decimalValue = decimalValue / 2;  // Update decimal value to the quotient
        }

        // Handle case when the input is 0 (special case)
        if (binaryString.isEmpty()) {
            binaryString = "0";
        }

        // Output the result
        System.out.println("Decimal: " + 43);
        System.out.println("Binary: " + binaryString);
    }
}

Output:

  • Decimal: 43
  • Binary: 101011