Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
15 years ago

Get integer value from character array

I have character arrays of 3 ascii characters representing range values from a sonar. I need to do some calculation on these values now. How can I convert the ascii char array to a valid integer

Ex. Char* [3] = {'2','5','5'} I need to convert to int = 255

Thanks

Chase

5 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    In C, you can just use the stdlib.h function ATOI. to convert ascii to integer. In HDL, you take each value, subtract 30, then mutiply by the correct power of ten multiplier to based on the bit location, then sum them all up,

    Pete
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Awesome the C method is what I was looking for. however, when I add the following call to convert...

    int Sonar_Height_Int = atoi(Sonar_Height);

    Where Sonar_Height is declared as char* Sonar_Height[3]

    because the sonar I am communicating with through uart sends data as a set of

    3 ascii char digits representing the range distance in inches.

    I get the following warning...

    passing arg 1 of `atoi' from incompatible pointer type

    What does this warning mean and in what way will it affect my program's performance?
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    char* Sonar_Height
    The above code declares an array of character pointers. I think you probably want an array of characters instead:
    char Sonar_Height
    Also, the atio function expects a NULL terminated string. You could increase the character array to length 4 and set the last character to NULL.

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Oh haha of course I see the mistake of the declaration now. Thank you so much for your assistance.

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Also look for strtoul() - which will tell you how much of the string was

    processed, allowing for much better error detecton.

    (But I'm not certain that it is in the lib that Altera provide.)