Java: Convert a decimal number to hexadecimal number
Decimal to Hexadecimal Converter
Write a Java program to convert a decimal number to a hexadecimal number.
Decimal number: The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is also called base-ten positional numeral system.
Hexadecimal number: Hexadecimal is a positional numeral system with a radix, or base, of 16. It 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.
Test Data:
Input a decimal number: 15
Pictorial Presentation: Decimal to Hexadecimal number
Sample Solution:
Java Code:
Explanation:
In the exercise above -
- It takes a decimal number ('dec_num') as input from the user using the "Scanner" class.
- It initializes an empty string 'hexdec_num' to store the hexadecimal representation and defines an array 'hex' containing hexadecimal digits (0-9 and A-F).
- It enters a loop to perform the decimal-to-hexadecimal conversion:
- In each iteration, it calculates the remainder of 'dec_num' when divided by 16 (which gives the hexadecimal digit) and appends it to the 'hexdec_num' string.
- It then updates 'dec_num' by dividing it by 16.
- The loop continues until 'dec_num' becomes zero, effectively converting the entire decimal number to hexadecimal.
- After the loop, it prints the hexadecimal representation of the decimal number stored in the 'hexdec_num' string.
Sample Output:
Input a decimal number: 15 Hexadecimal number is : F
Flowchart:
For more Practice: Solve these Related Problems:
- Convert a large decimal number (greater than 1000) to hexadecimal.
- Modify the program to allow the user to input multiple decimal numbers for conversion.
- Write a program to convert a decimal number to a hexadecimal number without using built-in functions.
- Convert a floating-point decimal number to a hexadecimal representation.
Go to:
PREV : Decimal to Binary Converter.
NEXT : Decimal to Octal Converter.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.