atoi实现

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.csdn.net/zwhlxl/article/details/47155963
http://arieshout.me/2012/03/implementation-of-atoi.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值