atoi implementation in C

前端 未结 6 1408
伪装坚强ぢ
伪装坚强ぢ 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 19:08

    k = (k << 3) + (k << 1);
    

    means

    k = k * 2³ + k * 2¹ = k * 8 + k * 2 = k * 10
    

    Does that help?

    The *p - '0' term adds the value of the next digit; this works because C requires that the digit characters have consecutive values, so that '1' == '0' + 1, '2' == '0' + 2, etc.

    As for your second question (atof), that should be its own question, and it's the subject for a thesis, not something simple to answer...

提交回复
热议问题