Java: Convert a hexadecimal to a binary number
Hexadecimal to Binary Converter
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
Sample Solution:
Java Code:
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:
For more Practice: Solve these Related Problems:
- Convert a hexadecimal number longer than four digits to binary.
- Modify the program to display the binary output in groups of four bits.
- Write a program that performs hexadecimal-to-binary conversion without using intermediate decimal conversion.
- Implement hexadecimal-to-binary conversion using bitwise operations.
Go to:
PREV : Hexadecimal to Decimal Converter.
NEXT :
Hexadecimal to Octal Converter.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.