atoi代码实现

来源:互联网 发布:ds18b20怎么接单片机 编辑:程序博客网 时间:2024/05/20 20:47
#include <stdio.h>#include <stdlib.h>long long StrToIntCore(const char* str, bool minus);enum Status {kValid = 0, kInvalid};int g_nStatus = kValid;int StrToInt(const char* str){    g_nStatus = kInvalid;    long long num = 0;    if(str != NULL && *str != '\0')     {        bool minus = false;        if(*str == '+')            str ++;        else if(*str == '-')         {            str ++;            minus = true;        }        if(*str != '\0')         {            num = StrToIntCore(str, minus);        }    }    return (int)num;}long long StrToIntCore(const char* digit, bool minus){    long long num = 0;    while(*digit != '\0')     {        if(*digit >= '0' && *digit <= '9')         {            int flag = minus ? -1 : 1;            num = num * 10 + flag * (*digit - '0');            if((!minus && num > 0x7FFFFFFF)                 || (minus && num < (signed int)0x80000000))            {                num = 0;                break;            }            digit++;        }        else         {            num = 0;            break;        }    }    if(*digit == '\0')     {        g_nStatus = kValid;    }    return num;}



bool g_nStatus = false;int StrToInt(const char *str){long long num = 0;if(str != NULL && *str != '\0'){bool minus = false;if(*str == '+')str++;else if(*str == '-'){minus = true;str++;}int flag = minus ? -1 : 1;if(*str != '\0'){while(*str != '\0'){if(*str >= '0' && *str <= '9'){num = num * 10 + flag * (*str - '0');if((minus && num < (signed int)0x80000000) || (!minus && num > 0x7FFFFFFF)){num = 0;break;}++str;}else{num = 0;break;}}if(*str == '\0')g_nStatus = true;}}return (int)num;}


0 0