I\'m learning C and I can\'t figure out one of the K&R exercises, the listing:
Exercise 2-3, Write the function
htoi(s)
, which conv
Recursion is not necessary. You simply need to loop backwards over the string (i.e. starting in the units column), summing the single digit conversion times it's radix position multiplier. This is pseudocode and does not handle the optional 0x prefix (and is not checking for possibility of overflow):
long total = 0;
long multiplier = 1;
for (int i = string.length - 1; i >= 0 i--)
{
digit = ConvertSingleHexDigittoInt(string[i]);
total += digit * multiplier;
multiplier *= 16;
}
I've left the easy implementation of ConvertSingleHexDigittoInt() to you :)