atoi atol实现
来源:互联网 发布:网络广播方案 编辑:程序博客网 时间:2024/06/05 20:39
看了atol的实现,发现char到int的转换比较奇怪:c = (int)(unsigned char)*nptr++; 先将char转为unsigned再转为int,于是测试了下,发现有如下结果:
void main()
{
char c = 0x80;
unsigned uc = 0x80;
printf("c2i=%x,c2ui=%x,uc2i=%x,uc2ui=%x\n", \
(int)c,(unsigned int)c,(int)uc,(unsigned int)uc
);
}
结果:
c2i=ffffff80,c2ui=ffffff80,uc2i=80,uc2ui=80
1. 跳过开头空格。
2. 判断第一个有效字符(非空格)是否是符号‘+’或‘-’。
3. 当遇到非数字时,函数结束,输出之前字串代表的整数。
4. 为严谨起见,就是文中提到的的char转int问题。
附atol源码:
void main()
{
char c = 0x80;
unsigned uc = 0x80;
printf("c2i=%x,c2ui=%x,uc2i=%x,uc2ui=%x\n", \
(int)c,(unsigned int)c,(int)uc,(unsigned int)uc
);
}
结果:
c2i=ffffff80,c2ui=ffffff80,uc2i=80,uc2ui=80
可以发现,如果char默认为signed(可能是平台相关的),则将char转为int或uint时,会有符号位扩展,而unsigned char则不会。atol/atoi函数应该希望避免符号位扩展而带来问题。不过,好在数字0到9的ACSII码并没有超过0x7F,因此是否事先转成unsigned char应该不会对结果有影响。
另,转一篇类似问题造成的BUG:http://testing.etao.com/node/217
1. 跳过开头空格。
2. 判断第一个有效字符(非空格)是否是符号‘+’或‘-’。
3. 当遇到非数字时,函数结束,输出之前字串代表的整数。
4. 为严谨起见,就是文中提到的的char转int问题。
附atol源码:
- long __cdecl atol(
- const char *nptr
- )
- {
- int c; /* current char */
- long total; /* current total */
- int sign; /* if '-', then negative, otherwise positive */
- /* skip whitespace */
- while ( isspace((int)(unsigned char)*nptr) )
- ++nptr;
- c = (int)(unsigned char)*nptr++;
- sign = c; /* save sign indication */
- if (c == '-' || c == '+')
- c = (int)(unsigned char)*nptr++; /* skip sign */
- total = 0;
- while (isdigit(c)) {
- total = 10 * total + (c - '0'); /* accumulate digit */
- c = (int)(unsigned char)*nptr++; /* get next char */
- }
- if (sign == '-')
- return -total;
- else
- return total; /* return result, negated if necessary */
- }
int atoi(const char *nptr){return (int)atol(nptr);}
- atoi atol实现
- atol(atoi)函数的实现要点
- atol(atoi)函数的实现要点
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转换
- atoi,atol,strtod,strtol,strtoul实现类型转
- C#读写ini文件操作
- 机器学习_算法_KNN
- JspServlet防止二次提交
- 约瑟夫环的数组实现方式
- 如何从零开始学习DIV+CSS
- atoi atol实现
- 3线双向零等待IO通讯机制
- sap obbh 浅谈
- LBS和AR技术
- 深入了解MTK方案之“Scatter”文件学习
- unity基础概念
- 创建自己的VIM GIT插件库
- wikioi p1163 访问艺术馆
- python实现单例模式,从始至终都只有一个实例