Linux requires the itoa function. Next I will provide a cross-platform itoa function.
// 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;
}
This function returns the length of the string, which is useful in some cases.
I tested it. This function is about 20% faster than the itoa provided by MFC.
(Because if (a> 9) does not need to be determined in the circular body, it is faster ).
2010/1/8 Ultimate Edition:
// 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;
}
Improvement: Change the division operation from a signed integer to an unsigned integer. The typical speed is increased from about 240 milliseconds to about 180 milliseconds. In comparison, it takes about 320 ms for the itoa provided by MFC.
(The Division of unsigned integers on x86 machines is faster, with different assembly commands)