64-bit shift issue

Why does this code not write 0 as the 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;
}
+3
source share
9 answers

When you change the value to more bits than the word size, it usually switches to mod word-size. Basically, a shift of 64 means a shift of 0 bits, which does not shift at all. You should not rely on this, although it is not defined by the standard, and it may be different on different architectures.

+13
source

By shifting a number, the number of bits that is equal to or greater than its width is undefined. You can safely shift a 64-bit integer from 0 to 63 positions.

+7

, . 0 64 , 65 . :

for(int i=0; i < 64; i++)
    ....
+1

:

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

, undefined?

+1

. , GCC :

warning: right shift count >= width of type

? 64 , undefined. 0 64, 65 ( 0). 0 - ( ).

#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;
}

.

+1

-1 0xFFFFFFFFFFFFFFFF 64- . , , , 64- , .. 18446744073709551615.

, , .. , , ( ).

0

: , , . 64- , 1 < < k, 1L < < k; : (

0
source

You can use:

static inline pack_t lshift_fix64(pack_t shiftee, short_idx_t shifter){ return (shiftee << shifter) & (-(shifter < 64)); } for such a trick, (-(shifter < 64)) == 0xffff ffff ffff ffffif shift <64 and (-(shifter < 64)) == 0x0otherwise.

0
source

Source: https://habr.com/ru/post/1710956/


All Articles