64bit shift problem

2020-03-24 08:09发布

Why this code does not write 0 as a last element but 18446744073709551615? (compiled with g++)

#include <iostream>

using namespace std;
int main(){
    unsigned long long x = (unsigned long long) (-1);
    for(int i=0; i <= 64; i++)
        cout << i << " " << (x >> i) << endl;
    cout << (x >> 64) << endl;
    return 0;
}

标签: c++ 64-bit
9条回答
啃猪蹄的小仙女
2楼-- · 2020-03-24 08:29

You overflow the shift. If you've noticed, GCC even warns you:

warning: right shift count >= width of type

How come? You include 64 as a valid shift, which is an undefined behavior. counting from 0 to 64 there are 65 numbers (0 included). 0 being the first bit (much like arrays).

#include <iostream>

using namespace std;
int main(){
    unsigned long long x = (unsigned long long) (-1);
    for(int i=0; i < 64; i++)
        cout << i << " " << (x >> i) << endl;
    cout << (x >> 63) << endl;
    return 0;
}

Will produce the output you'd expect.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-24 08:31

This warning from the compiler should be a hint:

"warning: right shift count >= width of type"

This results in undefined behavior:

http://sourcefrog.net/weblog/software/languages/C/bitshift.html

查看更多
干净又极端
4楼-- · 2020-03-24 08:39

I get:

test.c:8: warning: right shift count >= width of type

so perhaps it's undefined behavior?

查看更多
登录 后发表回答