w3resource

Java: Convert a hexadecimal to a binary number

Java Basic: Exercise-29 with Solution

Write a Java program to convert a hexadecimal number into a binary number.

Hexadecimal number: This is a positional numeral system with a radix, or base, of 16. Hexadecimal uses sixteen distinct symbols, most often the symbols 0-9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

Binary number: A binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).

Test Data:
Input any hexadecimal number: 37

Pictorial Presentation: Hexadecimal to Binary number

Java: Convert a hexadecimal to a binary number

Sample Solution:

Java Code:

import java.util.Scanner;

public class Exercise29 {
    // Function to convert a hexadecimal string to a decimal integer
    public static int hex_to_binary(String s) {
        // Define a string containing hexadecimal digits
        String digits = "0123456789ABCDEF";
        s = s.toUpperCase(); // Convert the input string to uppercase
        int val = 0; // Initialize the decimal value to 0

        // Iterate through each character in the input string
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i); // Get the current character
            int d = digits.indexOf(c); // Find the index of the character in the digits string
            val = 16 * val + d; // Update the decimal value using hexadecimal conversion
        }

        return val; // Return the decimal value
    }

    public static void main(String args[]) {
        String hexdec_num;
        int dec_num, i = 1, j;
        int bin_num[] = new int[100];
        Scanner scan = new Scanner(System.in);

        // Prompt the user to enter a hexadecimal number
        System.out.print("Enter Hexadecimal Number : ");
        hexdec_num = scan.nextLine();

        // Call the hex_to_binary function to convert the hexadecimal number to decimal
        dec_num = hex_to_binary(hexdec_num);

        // Convert the decimal number to binary
        while (dec_num != 0) {
            bin_num[i++] = dec_num % 2;
            dec_num = dec_num / 2;
        }

        // Display the equivalent binary number
        System.out.print("Equivalent Binary Number is: ");
        for (j = i - 1; j > 0; j--) {
            System.out.print(bin_num[j]);
        }

        System.out.print("\n");
    }
}

Explanation:

In the exercise above -

  • First, it defines a method "hex_to_decimal()" that takes a hexadecimal string 's' as input and converts it to its decimal equivalent.
  • The method initializes a string 'digits' containing the hexadecimal digits (0-9 and A-F) and ensures that the input string 's' is in uppercase to handle both uppercase and lowercase hexadecimal characters.
  • It initializes an integer variable 'val' to store the decimal value.
  • Next it iterates through each character 'c' in the input string 's' and finds the corresponding decimal value 'd' by looking up the index of 'c' in the 'digits' string.
  • It updates the 'val' by multiplying it by 16 and adding the decimal value 'd'.
  • The method returns the final decimal value 'val'.
  • In the "main()" function, it takes a hexadecimal number as input from the user using the "Scanner" class and stores it in the 'hexdec_num' string.
  • It calls the "hex_to_decimal()" method, passing 'hexdec_num' as an argument, to convert the hexadecimal string to its decimal equivalent and stores it in the 'dec_num' variable.
  • Finally, it prints the decimal representation of the original hexadecimal number stored in the 'dec_num' variable.

Sample Output:

Enter Hexadecimal Number : 37                                                                                 
Equivalent Binary Number is: 110111

Flowchart:

Flowchart: Java exercises: Convert a hexadecimal to a binary number

Java Code Editor:

Previous: Write a Java program to convert a hexadecimal to a decimal number.
Next: Write a Java program to convert a hexadecimal to a octal number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/basic/java-basic-exercise-29.php