// 自己参考并编写的itoa与atoi函数

// 支持10进制整形,支持16进制整形,支持负数

// 20220228,修复负数字符字符串会转换成正数的bug
#include <stdio.h>

char buffer[128];

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 */

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' + 0;
}
else if ('a' <= c && c <= 'f')
{
c = c - 'a' + 10;
}
else if ('A' <= c && c <= 'F')
{
c = c - 'A' + 10;
}
else
{
break;
}
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;
num = 0x234567;
printf("start.,%d,,,0x%x,,\r\n", num, num);
itoa(num, buffer, 16);
num = atoi(buffer);
printf("case 1::str=%s,,,num=0x%x,%d\n", buffer, num, num);

itoa(num, buffer, 10);
num = atoi(buffer);
printf("case 2::str=%s,,,num=0x%x,%d,\n", buffer, num,num);

num = -52;
printf("\r\n\r\nstart.,%d,,,0x%x,,\r\n", num, num);

itoa(num, buffer, 16);
num = atoi(buffer);
printf("case 3::str=%s,,,num=0x%x,%d\n", buffer, num,num);

itoa(num, buffer, 10);
num = atoi(buffer);
printf("case 4::str=%s,,,num=0x%x,,%d,\n", buffer, num,num);
}

 

Posted on 2022-02-26 22:57  污钞vtor  阅读(65)  评论(0编辑  收藏  举报