33,008
社区成员
发帖
与我相关
我的任务
分享
char* itoa(int n, int base)
{
// e.g. itoa(123, 10) returns the null-terminated
// string "123"
...
}
char* 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;
}