Thursday, 31 January 2013

ATOI implementation in C

// Program to implement own atoi function
#include <stdio.h>
int my_atoi(char *p) {     int k = 0;     while (*p) {         k = (k<<3)+(k<<1)+(*p)-'0';         p++; // Don't increment k     }     return k; }
int main(){     char pStr[] = "987";     int myNum = my_atoi(pStr);     printf(" myNum = %d\n", myNum);     return 0; }
Explanation: 1. k = (k<<3) + (k<<1) + (*p) - '0';  is equivalent to  k = k*10 + (*p) - '0'; 2. During first loop value of k is 0 and (*p) has value of char '9' ( ascii  - 57) and ascii of char '0' is 48. 3. Subtraction of them gives the integer value 9 ,stored in k. 4. Increment the pointer p, makes it points to char '8'. 5. Integer k is multiplied with 10  ( k<<3 + k<<1) and 8 is added to it making its value 98. 6. Again p is incremented and k finally stores integer 987.

No comments:

Post a Comment