atoi() is able to translate a string of a number into an integer number. There are lots of tech to do, and here is showing some examples.

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

10 times can be switched to bit-wise shift since bit-wise will use smaller instruction set which enables to reduce transistor in a system. Following shows of it.

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

  6 Responses to “Make your own atoi() function in C”

  1. New blog post: Make your own atoi() function in C http://blog.breadncup.com/2009/12/21/make-your-own-atoi-function-in-c/

  2. thanks for help
    can you please explain this string ?:

    => k = k*10 + (*p) – ’0′;

    • k holds an integer, and it is recalculated by looking at the each character from the beginning given p. (*p) tells you the character’s ASCII code and ’0′ as well. The difference gives the actual integer number. k*10 is shifting of previous value.

      For example, if p is given by “425″,

      The first calculation of k = 0*10 + (*p) – ’0′ = 0 + 52-48 = 4
      The next calculation of k = 4*10 + (*p) – ’0′ = 40 + 50 – 48 = 42
      The final calculation of k = 42*10 + (*p) – ’0′ = 420 + 53-48 = 425

      Character ASCII code of “4″ is 52, “2″ is 50, “5″ is 53, and “0″ is 48.

      Hope this would help you,
      Daniel

  3. Hi Daniel,

    I have this doubt about the code you posted, you said in one of the comments that k has an ASCII equivalent. Does the atoi version you wrote changes its behaviour if we use other encoding rather than ASCII?, say UTF-8.

    Great blog.


    Carlos

    • Thanks, Carlos.

      You’re right. It doesn’t support UTF-8, and the code I made was only for simple implementation showing how atoi() can be implemented, and it would be useful for job interview or some sort of things. It’s not fully for a product readiness or something like that.

      Thank you for your interest and pointing out of it.

      Daniel

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

 

December 2009
S M T W T F S
« Nov   Feb »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Follow Me

© 2011 Bread & Cup Suffusion theme by Sayontan Sinha