4

I'm currently working with a PLC that supports ANSI C, but uses its own flavour of the GNU compiler, which doesn't compile any variadic functions and things like itoa. So using sprintf & co. isn't an option for converting integers to strings. Can anyone guide me to a site where a robust, sprintf- free implementation of itoa is listed or post a suitable algorithm here? Thanks in advance.

2
  • 4
    So it does not support ANSI C. Commented Jan 26, 2010 at 8:34
  • 1
    Well yes. This is indeed an ongoing discussion with the SPC providers marketing department ;) Commented Jan 26, 2010 at 11:53

1 Answer 1

6

This is from K&R:

void itoa(int n, char s[])
{
    int i, sign;

    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
} 

reverse() just reverses a string.

Sign up to request clarification or add additional context in comments.

4 Comments

Use this version with care as it can overflow the buffer.
Yes, that's true. The caller has to know if the buffer has enough space or not. Just like sprintf().
Which is why you should never use sprintf() and only use snprintf()
I agree with you, if you replace "never" with "almost never". In general, one should prefer snprintf(). But if one is sure that the target buffer has the required size, sprintf() is fine too. See stackoverflow.com/questions/1996374/… for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.