March 08, 2024

Java Problem Solution: Convert a Decimal to Binary in Java and Convert a Binary to Decimal in Java


public class DecimalBinaryConversion {
    public static void main(String[] args) {
    	// Enter positive decimal or binary values only.
    	int decimal = 15;
        System.out.println("Decimal to Binary:");
        System.out.println("Decimal " + decimal + " -> Binary: " + decimalToBinary(decimal));
        String binary = "1110";
        System.out.println("\nBinary to Decimal:");
        System.out.println("Binary " + binary + " -> Decimal: " + binaryToDecimal(binary));
    }
    // Function to convert decimal to binary
    public static String decimalToBinary(int decimal) {
        StringBuilder binary = new StringBuilder();
        while (decimal > 0) {
            binary.insert(0, decimal % 2);
            decimal /= 2;
        }
        return binary.toString();
    }
    // Function to convert binary to decimal
    public static int binaryToDecimal(String binary) {
        int decimal = 0;
        int power = 0;
        for (int i = binary.length() - 1; i >= 0; i--) {
            if (binary.charAt(i) == '1') {
                decimal += Math.pow(2, power);
            }
            power++;
        }
        return decimal;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.