上篇文章说到linux需要itoa函数,下面我就提供一份跨平台的itoa函数。

这个函数会返回字符串的长度,在某些场合下会很有用。

//return the length of result string. support only 10 radix for easy use and better performance
int my_itoa(int val, char* buf)
{
    const unsigned int radix = 10;

    char* p;
    unsigned int a;        //every digit
    int len;
    char* b;            //start of the digit char
    char temp;
    unsigned int u;

    p = buf;

    if (val < 0)
    {
        *p++ = '-';
        val = 0 - val;
    }
    u = (unsigned int)val;

    b = p;

    do
    {
        a = u % radix;
        u /= radix;

        *p++ = a + '0';

    } while (u > 0);

    len = (int)(p - buf);

    *p-- = 0;

    //swap
    do
    {
        temp = *p;
        *p = *b;
        *b = temp;
        --p;
        ++b;

    } while (b < p);

    return len;
}

这个实现的典型速度大概是180毫秒左右。作为对比,MFC自带的itoa耗时是320毫秒左右。用snprintf的实现就不要出来比速度了,不是一个级别的。