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.
Do you learn better from video?
Learn faster with deeper understanding! 
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
rightmost 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: hextodecimal.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).
int
main(void)
{
char
hex[17];
int
length;
unsigned
long
decimal;
scanf("%16s",
hex);
length
= strlen(hex);
decimal
= hexToDecimal(hex, length);
printf("%s
in hexadecimal is %lu in decimal\n",
hex, decimal);
return
0;
}
unsigned
long
hexToDecimal(char
*hex, int
length)
{
int
i;
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;
}
return
decimal;
}
If you liked the hex to decimal lesson, you might want to review the decimal to hex or binary to decimal lessons.
Do you learn better from video?
Learn faster with deeper understanding! 
Did this help? Support me with your vote ;) 


Did this help? 

