itoa这个函数不是标准C库中的函数,有些编译器支持,如VS,有些却不支持,如GCC。这里参考网上资料修改了一个。
char* my_itoa(int i, int radix)
{
// 考虑了32位的二进制
static char local[33];
char *p = &local[32];
int sign = 0;
unsigned int tmp;
static unsigned char table[] = "0123456789abcdef";
if ( radix < 2 || radix > 16 )
{
*p = '\0';
return p;
}
// 十进制才有"负数"之说
if (i < 0 && radix == 10)
{
i = -i;
sign = 1;
}
// 其它进制,强制转换成无符号类型
tmp = i;
// 逆序保存
*p-- = '\0';
do {
*p-- = table[tmp % radix];
tmp /= radix;
} while (tmp > 0);
if (sign)
{
*p-- = '-';
}
return p + 1;
}
由于Windows平台的编译器支持itoa函数,所以用vs2003来测试,测试代码如下:
int my_itoa_test(void)
{
char* p;
int num = 125;
int neg_num = -125;
int radix = 0;
radix = 2;
p = my_itoa(num, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
p = my_itoa(neg_num, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 8;
p = my_itoa(num, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
p = my_itoa(neg_num, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 10;
p = my_itoa(num, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
p = my_itoa(neg_num, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 16;
p = my_itoa(num, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
p = my_itoa(neg_num, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
return 0;
}
int lib_itoa_test(void)
{
char p[33];
int num = 125;
int neg_num = -125;
int radix = 0;
radix = 2;
itoa(num, p, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
itoa(neg_num, p, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 8;
itoa(num, p, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
itoa(neg_num, p, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 10;
itoa(num, p, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
itoa(neg_num, p, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
radix = 16;
itoa(num, p, radix);
printf("num: %d radix: %d\t%s\n", num, radix, p);
itoa(neg_num, p, radix);
printf("num: %d radix: %d\t%s\n", neg_num, radix, p);
return 0;
}
int main(void)
{
printf("my itoa: \n");
my_itoa_test();
printf("\nhis itoa: \n");
lib_itoa_test();
return 0;
}
测试结果:
my itoa:
num: 125 radix: 2 1111101
num: -125 radix: 2 11111111111111111111111110000011
num: 125 radix: 8 175
num: -125 radix: 8 37777777603
num: 125 radix: 10 125
num: -125 radix: 10 -125
num: 125 radix: 16 7d
num: -125 radix: 16 ffffff83
his itoa:
num: 125 radix: 2 1111101
num: -125 radix: 2 11111111111111111111111110000011
num: 125 radix: 8 175
num: -125 radix: 8 37777777603
num: 125 radix: 10 125
num: -125 radix: 10 -125
num: 125 radix: 16 7d
num: -125 radix: 16 ffffff83
由测试结果知,上面自实现的函数能满足要求。至于性能,还没有深入研究。
网上资料很多,如下面的文章可以参考一下:
http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
迟 即日