itoa与atoi函数
// t1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include
char buffer[128];
void dec2str(char *buf, int num)
{
// 判断正负,提取负号,并纠正
// 得知当前数字有多少位,以float进行计算
int ee = 1000000000;
while (num / ee)
{
ee /= 10;
}
while (ee > 1)
{
ee /= 10;
*(buf++) = (num / ee) % 10 + '0';
}
}
char* itoa(int num, char* str, int radix)
{/*索引表*/
char index[] = "0123456789ABCDEF";
unsigned unum;/*中间变量*/
int i = 0, j, k = 0;
/*确定unum的值*/
if (radix == 10 && num < 0)/*十进制负数*/
{
unum = (unsigned)-num;
str[i++] = '-';
k = 1;
}
else if (radix == 16)
{
str[i++] = '0';
str[i++] = 'X';
k = 2;
unum = (unsigned)num;
}
else unum = (unsigned)num;/*其他情况*/
/*转换*/
do {
str[i++] = index[unum % (unsigned)radix];
unum /= radix;
} while (unum);
str[i] = '\0';
/*逆序*/
for (j = k; j <= (i) / 2; j++)
{
char temp;
temp = str[j];
str[j] = str[i - 1 + k - j];
str[i - 1 + k - j] = temp;
}
return str;
}
int atoi(const char *nptr)
{
int radix = 10;
int c; /* current char */
int total; /* current total */
int sign; /* if '-', then negative, otherwise positive */
/* skip whitespace */
while (isspace((int)(unsigned char)*nptr))
++nptr;
c = (int)(unsigned char)*nptr++;
sign = c; /* save sign indication */
if (c == '-' || c == '+')
c = (int)(unsigned char)*nptr++; /* skip sign */
// 判断十六进制,0x开头
if (c == '0'
&& (*nptr == 'x' || *nptr == 'X'))
{
radix = 16;
c = (int)(unsigned char)*nptr++; /* skip sign */
c = (int)(unsigned char)*nptr++; /* skip sign */
}
total = 0;
while (1)
{
if ('0' <= c && c <= '9')
{
c = c - '0';
}
else if ('a' <= c && c <= 'f')
{
c = c - 'a';
}
else if (('A' <= c && c <= 'F'))
{
c = c - 'A';
}
else
{
// 出现了意料之外的情况,直接退出当前函数
c = 0;
return total;
}
total = radix * total + c; /* accumulate digit */
c = (int)(unsigned char)*nptr++; /* get next char */
}
if (sign == '-')
return -total;
else
return total; /* return result, negated if necessary */
}
int main()
{
int num = 0x1234567;
printf("start.\r\n");
itoa(num, buffer, 16);
num = atoi(buffer);
printf("str=%s,,,num=%x,\n", buffer, num);
itoa(num, buffer, 16);
num = atoi(buffer);
printf("str=%s,,,num=%x,\n", buffer, num);
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件