ANSI C,整数到字符串没有可变参数函数

Nul*_*oid 4 c string integer itoa

我目前正在使用支持ANSI C的PLC,但使用自己的GNU编译器,它不会编译任何可变函数和itoa之类的东西.所以使用sprintf&co.不是将整数转换为字符串的选项.任何人都可以引导我到一个网站,其中列出了强大的,无sprintf的itoa实现或在此发布合适的算法?提前致谢.

Alo*_*hal 6

这是来自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);
} 
Run Code Online (Sandbox Code Playgroud)

reverse() 只是反转一个字符串.

  • 如果你用"几乎从不"取代"从不",我同意你的看法.通常,人们应该更喜欢`snprintf()`.但是如果确定目标缓冲区具有所需的大小,那么`sprintf()`也没关系.例如,请参见http://stackoverflow.com/questions/1996374/convert-integer-into-an-array/1996500#1996500. (2认同)