Here you can convert hex to decimal. You will also learn how the algorithm works. Finally, you will see how to write a small program in C that will read a hexadecimal number and convert it to decimal.
|Input the hexadecimal value||The decimal result is|
To better understand how the conversion works, you should read about the different numbering systems. If you already learned how to convert binary to decimal, this lesson will be easy for you. The two algorithms are almost identical.
Here is the hex to decimal algorithm:
Step 1: The coefficient of the
right-most digit is 1.
Step 2: Multiply the coefficient(1) by the value of the digit(2): 1*2 = 2
Step 3: The weight of the next digit is 1 * 16 = 16
Repeat 2: Multiply the coefficient(16) by the value of the digit(3): 16 * 3 = 48
Repeat 3: No more positions to calculate.
The result is the sum of the results.
You can download the source code of the example implementation from here: hex-to-decimal.zip
To read the hexadecimal value we use a character array of 17 elements. The last element is reserved for the string termination symbol, so we are left with 16 digits. This is just enough to save any 64 bit number. For that reason we use unsigned long to save the result.
Note that long is not guaranteed to be a 64 bit number. If your compiler supports C99, you can use the uint64_t type, which is defined in stdint.h
We read the input from the user and limit it to 16 characters to avoid an overflow. At this moment we should perform validation of the input, to make sure that it is a correct hexadecimal value. In this example we will skip the validation, so we can focus on the conversion itself. (The sample code in the zip has validation)
In the hexToDecimal function we use 3 additional variables:
We begin, by moving the
pointer to the last digit in the array:
hex += length – 1;
Then we organize the loop that will iterate over all digits. Inside the loop we just multiply the value of the digit by its coefficient and remember the result. The function valueOf returns the int value of the current digit (which is a char).
unsigned long decimal;
length = strlen(hex);
decimal = hexToDecimal(hex, length);
printf("%s in hexadecimal is %lu in decimal\n", hex, decimal);
unsigned long decimal = 0;
unsigned long weight = 1;
hex += length – 1;
for(i = length - 1; i >= 0; --i, --hex)
decimal += weight * valueOf(*hex);
weight *= 16;