C left shift on 64 bits fail

一曲冷凌霜 提交于 2019-11-26 22:04:48

问题


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\n", 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.


回答1:


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).




回答2:


I guess your problem is, you calculate with 32bit and assign it later to a 64 bit value

division by 64 is the same as not shift 6 bit

char x;
uint64_t one = 1;
uint64_t total = 0;

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

not compiled yet



来源:https://stackoverflow.com/questions/10048047/c-left-shift-on-64-bits-fail

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