c - atoi 在 C 中的实现

标签 c atoi atof

我看不懂下面的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 either str 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/

相关文章:

c - 发送免费 ARP 消息

c - atoi 从定义的索引将字符串转换为 char

c++ - 从字符串中提取单个字符并将其转换为 int

c++ - 双C++的算术错误

c++ - 在 Vector 上 push_back 时设置精度

使用 extern 编译错误

c - SO_RCVTIMEO 会影响 accept() 吗?

C - 即使所有分配都已释放,内存泄漏

C 字符值算术

c - char 到 float 的无效转换,不同的代码,没有好的结果