I can't understand the following atoi
implementation code, specifically this line: k = (k<<3)+(k<<1)+(*p)-'0';
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 ?
<<
is bit shift,(k<<3)+(k<<1)
isk*10
, written by someone who though he is more clever than a compiler (well, he was wrong...)(*p) - '0'
is substracting0
from the character pointed byp
, effectively converting the character to a number.I hope you can figure out the rest.. just remember how the decimal system works.
Note, that this is note a standard conforming
atoi
implementation. Sorry for not quoting the standard, but this will work just as fine (from: http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/ )Here is my implementation(tested successfully with cases containing and starting with letters, +, - and zero's). I tried to reverse-engineer atoi function in Visual Studio. If the input string only contained numerical characters, it could be implemented in one loop. but it gets complicated because you should take care of -,+ and letters.
means
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...Interestingly, the man page for atoi doesn't indicate setting of errno so if you're talking any number > (2^31)-1, you're out of luck and similarly for numbers less than -2^31 (assuming 32-bit int). You'll get back an answer but it won't be what you want. Here's one that could take a range of -((2^31)-1) to (2^31)-1, and return INT_MIN (-(2^31)) if in error. errno could then be checked to see if it overflowed.