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 .
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.
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;}
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 . 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 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