1、
表示字符常量,使用时,是转变换成字符对应的ASCII值. 如下,
‘0’对应的ASCII值: 48
‘1’——————–49
‘2’——————–50
.
‘9’——————–57
‘a’——————97
‘A’——————65
printf(“%d\n”,‘9’-‘3’);
2、
int 取值范围(4字节) 0x80000000 ~ 0x7fffffff(-2147483648 ~ 2147483647)
{
short int 占 2 字节 0x8000 ~ 0x7fff (-32768 ~ 32767)
-1 补码为 0xffff
-32768 补码 0x8000
-32767 补码 0x8001
}
3、
注意:
前面有空格,调过
要注意符号,即是正还是负数
非法输入
处理溢出
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#define INT_MAX ((int)0x7FFFFFFF)
#define INT_MIN ((int)0x80000000)
//#define INT_MAX (~(unsigned int)0/2)
int my_atoi(const char *str)
{
const char *s;
char c;
unsigned int cutoff;
int acc;
int neg, any, cutlim;
if(str == NULL)
{
errno = EINVAL;
return false;
}
s = str;
do{
c = *s++;
}while(c == ' ' || c == '\t');
if(c == '-'){
neg = 1;
c = *s++;
}
else
{
neg = 0;
if(c == '+')
c = *s++;
}
cutoff = neg? INT_MIN : INT_MAX;
cutlim = cutoff % 10;
cutoff /= 10;
acc = any = 0;
while(c >= '0' && c <= '9')
{
c -= '0';
if(acc > cutoff || (acc == cutoff && c > cutlim))
{
any = -1;
// printf("%d %d %d ",acc ,c ,acc*10+c);
break;
}
else
{
any = 1;
acc *= 10;
acc += c;
}
c = *s++;
}
if(any < 0)
{
errno = ERANGE;
// acc = neg? INT_MIN : INT_MAX;
acc= acc*10+c;
return acc;
}
else if(any == 0)
{
errno = EINVAL;
}
else if(neg)
{
acc = -acc;
}
return acc;
}
int main()
{
char a[] = "+2147483647";
printf("atoi(a)= %d \n",atoi(a));
printf("my_atoi(a)=%d \n",my_atoi(a));
return 0;
}
引用:
http://blog.youkuaiyun.com/zwhlxl/article/details/47155963
http://arieshout.me/2012/03/implementation-of-atoi.html