微软笔试题itoa
Convert integer to decimal representation
Write a function to convert an integer n into its ASCII string representation for a given base
The function must be implemented in a portable way that covers all possible values of n, and all bases between 2 and 16.
You are not allowed to use any library functions (given that this is a function that is included in the standard C library).
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;
}