Search code examples
catoiatof

atoi implementation in C


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

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

Here is the code:

int my_atoi(char *p) {
    int k = 0;
    while (*p) {
        k = (k << 3) + (k << 1) + (*p) - '0';
        p++;
     }
     return k;
}

Can someone explain it to me ?

Another question: what should be the algorithm of atof implementation ?


Solution

  • 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...