atoi implementation in C

前端 未结 6 1423
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 18:34

I can\'t understand the following atoi implementation code, specifically this line:

k = (k << 3) + (k << 1) + (*p) - \'0\';
<         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 18:59

    #include 
    #include 
    #include 
    
    double atof(const char *string);
    
    int debug=1;
    
    int main(int argc, char **argv)
    {
        char *str1="3.14159",*str2="3",*str3="0.707106",*str4="-5.2";
        double f1,f2,f3,f4;
        if (debug) printf("convert %s, %s, %s, %s\n",str1,str2,str3,str4);
        f1=atof(str1);
        f2=atof(str2);
        f3=atof(str3);
        f4=atof(str4);
    
        if (debug) printf("converted values=%f, %f, %f, %f\n",f1,f2,f3,f4);
        if (argc > 1)
        {
            printf("string %s is floating point %f\n",argv[1],atof(argv[1]));
        }
    }
    
    double atof(const char *string)
    {
        double result=0.0;
        double multiplier=1;
        double divisor=1.0;
        int integer_portion=0;
    
        if (!string) return result;
        integer_portion=atoi(string);
    
        result = (double)integer_portion;
        if (debug) printf("so far %s looks like %f\n",string,result);
    
        /* capture whether string is negative, don't use "result" as it could be 0 */
        if (*string == '-')
        {
            result *= -1; /* won't care if it was 0 in integer portion */
            multiplier = -1;
        }
    
        while (*string && (*string != '.'))
        {
            string++;
        }
        if (debug) printf("fractional part=%s\n",string);
    
        // if we haven't hit end of string, go past the decimal point
        if (*string)
        {
            string++;
            if (debug) printf("first char after decimal=%c\n",*string);
        }
    
        while (*string)
        {
            if (*string < '0' || *string > '9') return result;
            divisor *= 10.0;
            result += (double)(*string - '0')/divisor;
            if (debug) printf("result so far=%f\n",result);
            string++;
        }
        return result*multiplier;
    }
    

提交回复
热议问题