![]() |
VOOZH | about |
In this article, we will learn to write a C++ program to convert a decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.
In the decimal system, we use ten digits (0 to 9) to represent a number, while in the hexadecimal system, we use sixteen symbols (0 to 9 and A to F) to represent a number.
- Initialize a character array hexaDeciNum to store the hexadecimal representation.
- Run a loop till n is non-zero.
- Inside the loop,
- Initialize an integer variable temp to store the remainder and a character variable ch to store the converted hexadecimal character.
- Find the remainder of the number by taking mod by 16 (base of the hexadecimal system).
- Check if temp < 10, convert it to the corresponding ASCII character for the digit by adding 48 to the character, and store it in
hexaDeciNum. ('0' to '9' => ASCII 48 to 57).- Else, convert the current decimal number to the corresponding ASCII character for the digit by adding 55 to the digit, and storing it in
hexaDeciNum.- Update the number by dividing it by 16.
- Print the character array in reverse order.
The below diagram shows an example of converting the decimal number 2545 to an equivalent hexadecimal number.
9F1
If the given decimal number is 2545.
- Time complexity: O(log16n)
- Auxiliary space: O(1)
Refer to the complete article Program for decimal to hexadecimal conversion for more details.