Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

64bit shift problem

Tags:

c++

64-bit

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;
}
like image 297
Łukasz Lew Avatar asked Jun 21 '09 23:06

Łukasz Lew


2 Answers

When you shift a value by more bits than word size, it usually gets shifted by mod word-size. Basically, shifting it by 64 means shifting by 0 bits which is equal to no shifting at all. You shouldn't rely on this though as it's not defined by the standard and it can be different on different architectures.

like image 177
mmx Avatar answered Sep 24 '22 07:09

mmx


Shifting a number a number of bits that is equal to or larger than its width is undefined behavior. You can only safely shift a 64-bit integer between 0 and 63 positions.

like image 26
Tyler McHenry Avatar answered Sep 21 '22 07:09

Tyler McHenry