[C++] Linux下的itoa函数

上篇文章说到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 int radix = 10;

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

p = buf;

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

b = p;

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

*p++ = a + '0';

} while (val > 0);

len = (int)(p - buf);

*p-- = 0;

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

} while (b < p);

return len;
}

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

我测试了一下,这个函数大概比MFC自带的itoa要快20%左右。

(因为不需要在循环体内判断if (a > 9)了,所以更快)。

2010/1/8 改进版:

//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;
}

改进:将除法运算从有符号整数改为了无符号整数。典型速度从240毫秒左右,提高到了180毫秒左右。作为对比,MFC自带的itoa耗时是320毫秒左右。

(x86机器做无符号整数的除法要更快一些,汇编指令不同)

你可能感兴趣的:([C++] Linux下的itoa函数)