开发者

ANSI C, integer to string without variadic functions

开发者 https://www.devze.com 2022-12-17 08:40 出处:网络
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

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 c开发者_运维技巧onverting 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消