atoi implementation in C



我无法理解以下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'是从p所指向的字符中减去字符0的值,从而有效地将该字符转换为数字。

我希望你能弄清楚剩下的…记住十进制是如何工作的。

以下是标准函数atoi的规范。很抱歉没有引用标准,但这同样有效(来自:http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/)

函数首先丢弃尽可能多的空白字符(如isspace),直到第一个非空白字符建立然后,从这个字符开始,取一个可选的首字母加号或减号后面跟着尽可能多的以10为基数的数字,以及将它们解释为数值。

字符串可以在组成整数,它们被忽略,对行为没有影响这一功能。

如果str中的第一个非空白字符序列不是有效的整数,或者如果不存在这样的序列,因为str为空或仅包含空白字符,没有转换并返回零。

k = (k << 3) + (k << 1);

k = k * 2³ + k * 2¹ = k * 8 + k * 2 = k * 10

这有帮助吗?

*p - '0'项加上下一个数字的值;这是因为C要求数字字符具有连续值,因此'1' == '0' + 1'2' == '0' + 2等都是

至于你的第二个问题(atof),这应该是它自己的问题,它是论文的主题,而不是简单的答案。。。

#include <stdio.h>
#include <errno.h>
#include <limits.h>
double atof(const char *string);
int debug=1;
int main(int argc, char **argv)
{
char *str1="3.14159",*str2="3",*str3="0.707106",*str4="-5.2";
double f1,f2,f3,f4;
if (debug) printf("convert %s, %s, %s, %sn",str1,str2,str3,str4);
f1=atof(str1);
f2=atof(str2);
f3=atof(str3);
f4=atof(str4);
if (debug) printf("converted values=%f, %f, %f, %fn",f1,f2,f3,f4);
if (argc > 1)
{
printf("string %s is floating point %fn",argv[1],atof(argv[1]));
}
}
double atof(const char *string)
{
double result=0.0;
double multiplier=1;
double divisor=1.0;
int integer_portion=0;
if (!string) return result;
integer_portion=atoi(string);
result = (double)integer_portion;
if (debug) printf("so far %s looks like %fn",string,result);
/* capture whether string is negative, don't use "result" as it could be 0 */
if (*string == '-')
{
result *= -1; /* won't care if it was 0 in integer portion */
multiplier = -1;
}
while (*string && (*string != '.'))
{
string++;
}
if (debug) printf("fractional part=%sn",string);
// if we haven't hit end of string, go past the decimal point
if (*string)
{
string++;
if (debug) printf("first char after decimal=%cn",*string);
}
while (*string)
{
if (*string < '0' || *string > '9') return result;
divisor *= 10.0;
result += (double)(*string - '0')/divisor;
if (debug) printf("result so far=%fn",result);
string++;
}
return result*multiplier;
}

有趣的是,atoi的手册页没有指示errno的设置,所以如果你说的是任何大于(2^31)-1的数字,那么你就运气不好了,对于小于-2^31的数字(假设32位int)也是如此。你会得到一个答案,但这不是你想要的。这是一个可以取值范围为-((2^31)-1)到(2^3)-1的函数,如果有错误,则返回INT_MIN(-(2^1))。然后可以检查errno是否溢出。

#include <stdio.h>
#include <errno.h>  /* for errno */
#include <limits.h> /* for INT_MIN */
#include <string.h> /* for strerror */
extern int errno;
int debug=0;
int atoi(const char *c)
{
int previous_result=0, result=0;
int multiplier=1;
if (debug) printf("converting %s to integern",c?c:"");
if (c && *c == '-')
{
multiplier = -1;
c++;
}
else
{
multiplier = 1;
}
if (debug) printf("multiplier = %dn",multiplier);
while (*c)
{
if (*c < '0' || *c > '9')
{
return result * multiplier;
}
result *= 10;
if (result < previous_result)
{
if (debug) printf("number overflowed - return INT_MIN, errno=%dn",errno);
errno = EOVERFLOW;
return(INT_MIN);
}
else
{
previous_result *= 10;
}
if (debug) printf("%cn",*c);
result += *c - '0';
if (result < previous_result)
{
if (debug) printf("number overflowed - return MIN_INTn");
errno = EOVERFLOW;
return(INT_MIN);
}
else
{
previous_result += *c - '0';
}
c++;
}
return(result * multiplier);
}
int main(int argc,char **argv)
{
int result;
printf("INT_MIN=%d will be output when number too high or too low, and errno setn",INT_MIN);
printf("string=%s, int=%dn","563",atoi("563"));
printf("string=%s, int=%dn","-563",atoi("-563"));
printf("string=%s, int=%dn","-5a3",atoi("-5a3"));
if (argc > 1)
{
result=atoi(argv[1]);
printf("atoi(%s)=%d %s",argv[1],result,(result==INT_MIN)?", errno=":"",errno,strerror(errno));
if (errno) printf("%d - %sn",errno,strerror(errno));
else printf("n");
}
return(errno);
}

这是我的实现(成功地测试了包含字母、+、-和零的用例)。我尝试在VisualStudio中对atoi函数进行反向工程。如果输入字符串只包含数字字符,则可以在一个循环中实现。但它会变得复杂,因为你应该处理-+和字母。

int atoi(char *s)
{    
int c=1, a=0, sign, start, end, base=1;
//Determine if the number is negative or positive 
if (s[0] == '-')
sign = -1;
else if (s[0] <= '9' && s[0] >= '0')
sign = 1;
else if (s[0] == '+')
sign = 2;
//No further processing if it starts with a letter 
else 
return 0;
//Scanning the string to find the position of the last consecutive number
while (s[c] != 'n' && s[c] <= '9' && s[c] >= '0')
c++;
//Index of the last consecutive number from beginning
start = c - 1;
//Based on sign, index of the 1st number is set
if (sign==-1)       
end = 1;
else if (sign==1)
end = 0;
//When it starts with +, it is actually positive but with a different index 
//for the 1st number
else
{ 
end = 1;
sign = 1;
}
//This the main loop of algorithm which generates the absolute value of the 
//number from consecutive numerical characters.  
for (int i = start; i >=end ; i--)
{
a += (s[i]-'0') * base;
base *= 10;
}
//The correct sign of generated absolute value is applied
return sign*a;
}

关于atoi()提示代码:

基于atoi(),我实现了atof():

[具有与原始代码相同的限制,不检查长度等]

double atof(const char* s)
{
double value_h = 0;
double value_l = 0;
double sign = 1;
if (*s == '+' || *s == '-')
{
if (*s == '-') sign = -1;
++s;
}
while (*s >= 0x30 && *s <= 0x39)
{
value_h *= 10;
value_h += (double)(*s - 0x30);
++s;
}
// 0x2E == '.'
if (*s == 0x2E)
{
double divider = 1;
++s;
while (*s >= 0x30 && *s <= 0x39)
{
divider *= 10;
value_l *= 10;
value_l += (double)(*s - 0x30);
++s;
}
return (value_h + value_l/divider) * sign;
}
else
{
return value_h * sign;
}
}

最新更新