How to convert a decimal number to hexadecimal in C
A decimal is a term that describes the base- number system; for example,
A hexadecimal is a term that describes the base- number system.
The digits used in hexadecimal are , followed by , where represents the decimal number , represents , and so on up to representing .
Decimal to hexadecimal conversion
Step 1: Start by entering the decimal number provided.
Step 2: Divide the decimal value by .
Step 3: Convert the remainder obtained in Step 2 to the equivalent hexadecimal digit. If the remaining is less than , the remainder should be used as the hexadecimal digit. Use the matching letter instead, where represents , represents , and so on.
Step 4: Add the hexadecimal digit received to the front of the result.
Step 5: Steps 2–4 must be repeated until the decimal number reaches zero.
Step 6: The hexadecimal representation of the original decimal number is obtained as a result.
Example: Convert the decimal number into hexadecimal.
Code example
The following code shows the conversion from decimal to hexadecimal.
#include <stdio.h>void decToHex(int decimal){if (decimal == 0){printf("Hexadecimal: 0\n");return;}char hexadecimal[100];int indx = 0;while (decimal > 0){int remainder = decimal % 16;if (remainder < 10)hexadecimal[indx++] = remainder + '0';elsehexadecimal[indx++] = remainder + 'A' - 10;decimal /= 16;}printf("Hexadecimal number is: ");for (int i = indx - 1; i >= 0; i--)printf("%c", hexadecimal[i]);printf("\n");}int main(){int decimalNum = 27;decToHex(decimalNum);return 0;}
Code explanation
-
Lines 5–9: The
ifcondition determines whether the input decimal is equal to zero. If it is, the hexadecimal representation is also zero, and the function outputs"Hexadecimal: 0"and returns. -
Lines 18–21: The
if-elsecondition determines whether the remainder is less than . If it is, the remainder is in the range, and the matching hexadecimal digit may be derived by adding the remainder to the ASCII value'0'. If the remainder is more than or equal to , the hexadecimal digits are . In this situation, the remainder is calculated by subtracting10and adding it to the ASCII value'A'. -
Lines 28–29: The
forloop iterates through the hexadecimal array in reverse order, beginning at the highest indexindx - 1and ending at0. The format specifier%cis used to print each hexadecimal digit. -
Lines 34–39: The
mainfunction assigns the value27to the integer variabledecimalNum. It then runs thedecToHexmethod with the inputdecimalNumto convert it into hexadecimal.
Free Resources