Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5707785
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2008-01-24 16:18:52

在写程序的时候,我们经常使用到atoi()这个函数将命令行参数转化为数字。

今天在写程序的时候,使用命令行参数传递数据包的seq来构造数据包,发现构造的总不是自己输入的数。考虑可能是atoi()的问题,在程序里面打印atoi()之后的结果,发现果然不对。

仔细查了一下,atoi()转化成一个signed int,是有符号的,范围是-2G~+2G。如果我们输入的是一个大于2G的数的话,就会有问题。

       The call atoi(str) shall be equivalent to:

              (int) strtol(str, (char **)NULL, 10)

       except  that  the handling of errors may differ. If the value cannot be
       represented, the behavior is undefined.

atoi()是使用strtol()来实现的。

有strto*这么一族函数,以前没有怎么用过,看一下:
wangyao@wangyao-desktop:~/Public$ man strto
strtod     strtoimax  strtok_r   strtold    strtoul    strtoumax 
strtof     strtok     strtol     strtoll    strtoull 

我们使用strtoul()来实现一个atou()。

unsigned int atou(char *str)
{
    return strtoul(str,NULL,10);
}

我写了一个程序测试一下:
#include
#include

unsigned int atou(char *str)
{
        return strtoul(str, NULL, 10);
}

int main(int argc, char *argv[])
{
        printf("argv[1]: %s\n", argv[1]);
        printf("atoi: %u\n", atoi(argv[1]));
        printf("atou: %u\n", atou(argv[1]));

        return 0;
}


结果如下:
wangyao@wangyao-desktop:~$ ./a.out 2430046651
argv[1]: 2430046651
atoi: 2147483647
atou: 2430046651

阅读(10410) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~