我看不懂下面的atoi
实现代码,特别是这一行:
k = (k << 3) + (k << 1) + (*p) - '0';
代码如下:
int my_atoi(char *p) {
int k = 0;
while (*p) {
k = (k << 3) + (k << 1) + (*p) - '0';
p++;
}
return k;
}
有人能给我解释一下吗?
另一个问题:atof
实现的算法应该是什么?
最佳答案
<<
是位移位,(k<<3)+(k<<1)
是k*10
,由自认为比编译器更聪明的人编写(好吧,他错了......)
(*p) - '0'
正在减去字符 0
的值来自 p
指向的字符, 有效地将字符转换为数字。
我希望你能弄清楚剩下的...只要记住十进制是如何工作的。
这是标准函数的规范 atoi
.很抱歉没有引用标准,但这同样有效(来自:http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/)
The function first discards as many whitespace characters (as in
isspace
) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in
str
is not a valid integral number, or if no such sequence exists because eitherstr
is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
关于c - atoi 在 C 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791077/