strtoull and long long arithmetic

天涯浪子 提交于 2019-12-17 21:28:26

问题


Can anyone explain the output of this program and how I can fix it?

unsigned long long ns = strtoull("123110724001300", (char **)NULL, 10);
fprintf(stderr, "%llu\n", ns);

// 18446744073490980372

回答1:


Do you have <stdlib.h> included?

I can reproduce on MacOS X if I omit <stdlib.h>.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    unsigned long long ns = strtoll("123110724001300", (char **)NULL, 10);
    printf("%llu\n", ns);
    return(0);
}

Omit the header, I get your result. Include the header, I get the correct answer.

Both 32-bit and 64-bit compiles.


As noted in the comments, in the absence of a declaration for strtoll(), the compiler treats it as a function returning int.

To see more of what goes on, look at the hex outputs:

     123110724001300    0x00006FF7_F2F8DE14    Correct
18446744073490980372    0xFFFFFFFF_F2F8DE14    Incorrect

Manually inserted underscores...




回答2:


Why not use strtoull if you want an unsigned long long?




回答3:


I cannot explain the behavior. However, on 32 bit Windows XP with Cygwin gcc-4.3.2:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    unsigned long long ns = strtoull("123110724001300", NULL, 10);
    fprintf(stderr, "%llu\n", ns);
    return 0;
}

prints

E:\Home> t.exe
123110724001300


来源:https://stackoverflow.com/questions/1646031/strtoull-and-long-long-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!