atoi implementation in C

前端 未结 6 1424
伪装坚强ぢ
伪装坚强ぢ 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:53

    about atoi() hint code from here:

    and based on the atoi(), my implementation of atof():

    [have same limitation of original code, doesn't check length, etc]

    double atof(const char* s)
    {
      double value_h = 0;
      double value_l = 0;
      double sign = 1;
    
      if (*s == '+' || *s == '-')
      {
        if (*s == '-') sign = -1;
        ++s;
      }
    
      while (*s >= 0x30 && *s <= 0x39)
      {
        value_h *= 10;
        value_h += (double)(*s - 0x30);
        ++s;
      }
    
      // 0x2E == '.'
      if (*s == 0x2E)
      {
        double divider = 1;
        ++s;
        while (*s >= 0x30 && *s <= 0x39)
        {
          divider *= 10;
          value_l *= 10;
          value_l += (double)(*s - 0x30);
          ++s;
        }
        return (value_h + value_l/divider) * sign;
      }
      else
      {
        return value_h * sign;
      }
    }
    

提交回复
热议问题