itoa是windows的标准函数,但在linux系统中并未作为标准实现。这些天写了一个linux版本的测试例子,其中需要用到itoa函数,所以自己实现了一下。目前该函数只有
base为10的版本,其实现思路大致为:
1)首先判断待转换整数的符号,并且对负数最大值做记录(如果为INT_MIN,则positive_add被赋值为1)。
2)循环将待转换整数模10,直至待转换整数等于0。这里采用了do while循环,是为了保证当待转换整数为0时,依然可以执行一次循环。3)第二步得到的数是反序的,所以此时需要将结果倒转回来,被拷贝到输出buf中。
下面是代码:
static void MyItoA10(int val, char* buf, int buf_len)
{
static char buf_convert[11] = {0};
char* buf_convert_ptr = buf_convert;
bool positive_val = false;
int positive_add = 0;
if (val < 0) {
positive_val = true;
if (val == INT_MIN) {
val = INT_MAX;
positive_add = 1;
} else {
val = -val;
}
}
do {
if (buf_convert_ptr == buf_convert && positive_add) {
*buf_convert_ptr++ = (val % 10) + '1';
} else {
*buf_convert_ptr++ = (val % 10) + '0';
}
val /= 10;
} while (val);
if (positive_val) {
*buf_convert_ptr++ = '-';
}
// Revise content into buf.
char* buf_ptr_revise = buf_convert_ptr - 1;
char* buf_dest = buf;
while (buf_ptr_revise >= buf_convert && buf_dest - buf < buf_len - 1) {
*buf_dest++ = *buf_ptr_revise--;
}
// Add tailing char.
*buf_dest = '\0';
}
接下来是测试函数。
int main()
{
static const int knTestArray[] = {
0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000,
999999, 1000000, 9999999, 10000000, 99999999, 100000000,
INT_MAX,
-1, -9, -10, -99, -100, -999, -1000, -9999, -10000, -99999, -100000,
-999999, -1000000, -9999999, -10000000, -99999999, -100000000,
INT_MIN,
};
static const char* knResultArray[] = {
"0", "1", "9", "10", "99", "100", "999", "1000", "9999", "10000", "99999", "100000",
"999999", "1000000", "9999999", "10000000", "99999999", "100000000",
"2147483647",
"-1", "-9", "-10", "-99", "-100", "-999", "-1000", "-9999", "-10000", "-99999", "-100000",
"-999999", "-1000000", "-9999999", "-10000000", "-99999999", "-100000000",
"-2147483648",
};
for (int i = 0; i < sizeof(knTestArray) / sizeof(knTestArray[0]); ++i) {
char* dest = new char[strlen(knResultArray[i]) + 1];
MyItoA10(knTestArray[i], dest, strlen(knResultArray[i]) + 1);
assert(strcmp(dest, knResultArray[i]) == 0);
delete dest;
} // for.
std::cin.get();
}