有意思的atoll函数

来源:互联网 发布:广东国税申报软件 编辑:程序博客网 时间:2024/06/03 14:12

有这样一个测试程序:

#include <stdio.h>

#include <sys/types.h>


 

int main(void)
{
        char *str =  "4000000000";

        int64_t a = 0;

 

        a = atoll(str);

        printf("a = %lld/n", a);
        printf("a = %llu/n", a);
}

 

结果会是怎样?

结果是这样:

a = -294967296
a = 18446744073414584320

 

如果代码修改为:

#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h> //Only she can resolve this problem 
 

int main(void)
{
        char *str =  "4000000000";

        int64_t a = 0;

 

        a = atoll(str);

        printf("a = %lld/n", a);
        printf("a = %llu/n", a);
}

结果正确了:

a = 4000000000
a = 4000000000

 

是不是很神奇?

经过对两段代码汇编跟踪,发现出错的代码别输出正确的代码多了一个sar的命令

sarl $0x1f %edx

这条指令是将64位数的高32为向右移动31位。因为40亿这个数高位是1,所以整个高32会被1填满。(我的天,知道为什么要这么做?)

看来是用atoll函数还是要慎重,注意引用头文件。不然错了都不知道怎么回事。

 

原创粉丝点击