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;
}
New blog post: Make your own atoi() function in C http://blog.breadncup.com/2009/12/21/make-your-own-atoi-function-in-c/
New blog post: Make your own atoi() function in C http://blog.breadncup.com/2009/12/21/make-your-own-atoi-function-in-c/
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
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