Search code examples
catoi

Atoi function in C?


int atoi(char* s)
{
   int i,n;
   n=0;
   for (i=0; (s[i]>='0') && (s[i]<='9'); i++)
       n = 10 * n + (s[i] - '0');

   return n;
}

In this code what is s[i]-'0' doing? Can anyone please explain the detailed working of this function?


Solution

  • Have a look at the table in the link below-

    http://www.asciitable.com/

    The table is called ASCII Table and it is one of the character-encoding schemes used to represent characters in the binary world.

    You can see the decimal numbers 0-9 are represented by numbers 48-57 in the ASCII table. All digits(0-9) are stored as characters.

    If your computer stores 48 for decimal number 0, 49 for decimal number 1, 50 for decimal number 2 and so-on. Then, to convert a ASCII number into decimal number, you just need to subtract 48 from ASCII number. For example,

    48 - 48 => 0

    49 - 48 => 1

    50 - 48 => 2

    .. and so-on

    '0' also represents 48. It is a character form of number 48. That's why, the equation n = 10 * n + (s[i] - '0'); has '0'.