函数 atoi() 和 itao() 的 C 语言实现。 1. atoi() 函数 #include <stdio.h> #include <stdlib.h> #include <ctype.h> int myatoi(const char *str) { int c; int total; int sign; while(isspace((int)(unsigned char)*str)){ ++str; } c = (int)(unsigned char)*str++; sign = c; if(c == '-' || c == '+'){ c = (int)(unsigned char)*str++; } total = 0; while(isdigit(c)){ total = total * 10 + (c - '0'); c = (int)(unsigned char)*str++; } if(sign == '-'){ return -total; } else{ return total; } } int main() { char *str = "-1234567"; int result = myatoi(str) + 10000; printf("%d/n", result); return 0; } 稍做修改后代码: #include <stdio.h> #include <stdlib.h> #include <ctype.h> int atoi_test(const char *str) { char c; char sign; int total; while(isspace(*str)){ ++str; } c = *str++; sign = c; if( c == '-' || c == '+'){ c = *str++; } total = 0; while(isdigit(c)){ total = total * 10 + (c - '0'); c = *str++; } if(sign == '-'){ return -total; } else{ return total; } } int main() { char *str = "-5234"; int result = atoi_test(str); printf("%d/n", result); return 0; } 2. itoa() 函数 #include <stdio.h> #include <stdlib.h> #include <errno.h> char *myitoa(int value, char *string, int radix) { char temp[33]; char *tp = temp; int i; unsigned int v; int sign; char *sp; if(radix > 36 || radix <= 1){ // set_errno(EDOM); return 0; } sign = (radix == 10 && value < 0); if (sign){ v = -value; } else{ v = (unsigned)value; } while(v || tp == temp){ i = v % radix; v = v / radix; if(i < 10){ *tp++ = i + '0'; } else{ *tp++ = i + '0' - 10; } } if(string == 0){ string = (char *)malloc((tp-temp)+sign+1); } sp = string; if(sign){ *sp++ = '-'; } while(tp > temp){ *sp++ = *--tp; } *sp = 0; return string; } int main() { int aa = -234500000; char result[33]; myitoa(aa, result, 10); printf("%s/n", result); return 0; } 稍做修改后代码: #include <stdio.h> #include <stdlib.h> #include <ctype.h> char *itoa_test(int num) { int i; int value; bool sign; char *string; string = (char *)malloc(30); char *tmp = string; if(num < 0){ sign = false; value = -num; } else{ sign = true; value = num; } while(value > 0){ i = value % 10; value = value / 10; if(i < 10){ *tmp = i + '0'; } else{ *tmp = i + '0' - 10; } tmp++; } char *pos = (char *)malloc(30); char *result = pos; if(!sign){ *pos++ = '-'; } while(string < tmp){ *pos++ = *--tmp; } return result; } int main() { int aa= -12340560; char *result = itoa_test(aa); printf("%s/n", result); return 0; }