hex2dec conversion

Hi, it's just a small bug but I can't figure it out. Please help

I receive a series of HEX value as a char array (something like: '0','x','4','2','TAB', '0', 'x', 'A', 'D','TAB'... ) from the serial port. And I can extract the useful information like '4','2' and 'A','D' as small char arrays. Now I use the following function to convert it to decimal values:

int hexstring_to_dec(char* input, int lengths){
  int result = 0;
  for(int i=lengths-1; i>=0; i--){
    result = result + hex_to_dec(input[i])*pow(16,(lengths-1)-i);
    }
   return result;
  }

hex_to_dec is just a function mapping '0'-'F' to 0-15;

The problem is: if the incoming hex value is single digit, the output is correct. i.e. 'A' will get 10, '0','4' will get 4. But if it's multidigit, the result is always 1 smaller than what it should be. i.e. '4','2' will get 65 not 66, '5','0','1' will get 1280 not 1281.
I guess it's not the mathematical or algorithm thing that cause the '-1'. Can anyone see the problem?

Thanks in advance.

Don't use pow(). It's for floats and works by approximation. When you cast the result to an int the fractional part is brusquely discarded and you're left with a number one less than you expected.

GypsumFantastic:
Don't use pow(). It's for floats and works by approximation. When you cast the result to an int the fractional part is brusquely discarded and you're left with a number one less than you expected.

Thanks, then how should I do the power, Arduino doesn't recognize '^'.

How about something like this (code untested):

for(int i=0; i<lengths; i++)
{
    result = result*16 + hex_to_dec(input[i]);
}

GypsumFantastic:
How about something like this (code untested):

for(int i=0; i<lengths; i++)

{
    result = result*16 + hex_to_dec(input[i]);
}

Cool, it solves the problem.
But I still can't understand why pow() will get error. All the inputs are int and it's only addition and multiplication which won't make any fraction but just xx.00

wxs:
But I still can't understand why pow() will get error. All the inputs are int

pow()'s internal workings are all floats, and so are subject to a tiny bit of rounding error. If you stay with floats this is OK, but if you make that an int, you lose the fractional part entirely. 99.99999 will turn into 99.

it's only addition and multiplication which won't make any fraction but just xx.00

That's not correct I'm afraid. You can't do fractional exponents with just multiplication. pow() expects fractions, so is set up to do it using (if I remember it right) logarithms, which are calculated by approximation in C(++).