C標準ライブラリatoi関数の実現
9385 ワード
/*
* atoi
* int
* :
* 1
* 2
* 3
* 4
*/
#include
/*
int atoi(const char *str) {
char *p = (char *)str;
int ret = 0;
int retPre = 0;
int over_flow = 1<int)*8-1);
int sign = 1;
int base = 10;
//
while (*p==' ' || *p=='\t') {
++p;
}
//
if (*p=='-') sign = -1, ++p;
else if (*p=='+') sign = 1, ++p;
else sign = 1;
//
if (*p=='0' && *(p+1)=='x' || *(p+1)=='X') base=16, p+=2;
else if(*p=='0') base=8, ++p;
else base = 10;
while (*p != '\0') {
retPre = ret;
if ((*p>='0'&&*p<='7') || (base!=8&&*p>='8'&&*p<='9')) {
ret *= base;
ret += *p - '0';
}
else if (base==16 && ((*p>='a' && *p<='f') || (*p>='A' && *p<='F'))) {
ret *= base;
switch (*p) {
case 'a': case 'A': ret += 10; break;
case 'b': case 'B': ret += 11; break;
case 'c': case 'C': ret += 12; break;
case 'd': case 'D': ret += 13; break;
case 'e': case 'E': ret += 14; break;
case 'f': case 'F': ret += 15; break;
default: break;
}
}
else {
break;
}
//
if (sign==-1 && ret==over_flow) {
break;
}
else if ((ret&over_flow)==over_flow) {
ret = retPre;
break;
}
++p;
}
if (sign==-1) ret = -ret;
return ret;
}
*/
int atoi(const char *str) {
char *p = (char *)str;
int ret = 0;
int sign;
//
while (*p==' ' || *p=='\t') {
++p;
}
//
if (*p=='-') sign = -1, ++p;
else if (*p=='+') sign = 1, ++p;
else sign = 1;
//
while (*p>='0' && *p<='9') {
ret *= 10;
ret += *p - '0';
++p;
}
if (sign==-1) ret = -ret;
return ret;
}
int main() {
printf("%d
", atoi(" -2147483648002"));
printf("%d
", atoi(" -2147483650"));
printf("%d
", atoi(" 2147483647"));
printf("%d
", atoi(" 2147483648"));
printf("%d
", atoi(" 012"));
printf("%d
", atoi(" 10"));
printf("%d
", atoi(" 0xa"));
return 0;
}