How to convert a decimal number to hexadecimal in C

A decimal is a term that describes the base-1010 number system; for example, (47)10(47)_{10}

A hexadecimal is a term that describes the base-1616 number system.

The digits used in hexadecimal are 090–9, followed by AFA–F, where AA represents the decimal number 1010, BB represents 1111, and so on up to FF representing 1515.

Decimal to hexadecimal conversion

Step 1: Start by entering the decimal number provided.

Step 2: Divide the decimal value by 1616.

Step 3: Convert the remainder obtained in Step 2 to the equivalent hexadecimal digit. If the remaining is less than 1010, the remainder should be used as the hexadecimal digit. Use the matching letter AFA-F instead, where AA represents 1010, BB represents 1111, 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 1000101000_{10} into hexadecimal.

1 of 4

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';
else
hexadecimal[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 if condition 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-else condition determines whether the remainder is less than 1010. If it is, the remainder is in the 090–9 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 1010, the hexadecimal digits are AFA–F. In this situation, the remainder is calculated by subtracting 10 and adding it to the ASCII value 'A'.

  • Lines 28–29: The for loop iterates through the hexadecimal array in reverse order, beginning at the highest index indx - 1 and ending at 0. The format specifier %c is used to print each hexadecimal digit.

  • Lines 34–39: The main function assigns the value 27 to the integer variable decimalNum. It then runs the decToHex method with the input decimalNum to convert it into hexadecimal.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved