Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

64 bit - C left shift on 64 bits fail

I have this code in C (it's for study only):

    char x;
    uint64_t total = 0;

    for(x = 20; x < 30; x++){
        total = (((((1 << x) * x) / 64) + 1) * sizeof(uint64_t));
        printf("%d - %llu
", x, total);        
    }       

What is printed:

20 - 2621448
21 - 5505032
22 - 11534344
23 - 24117256
24 - 50331656
25 - 104857608
26 - 218103816
27 - 18446744073625665544
28 - 18446744073575333896
29 - 18446744073508225032

Why at x > 26 do I have those strange values? I'm at gcc 4.6.1 on Ubuntu 10.10 64 bits.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because 1 is an int, 32 bits, so (1 << 27)*27 overflows. Use 1ull.

Regarding your comment, if x is a uint64_t, then 1 << x is still an int, but for the multiplication it would be cast to uint64_t, so there'd be no overflow. However, if x >= 31, 1 << x would be undefined behaviour (as the resulting value cannot be represented by a signed 32 bit integer type).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...