-1

When i use shift left in uint64_t variable, like mask = 1 << 31 or above, all bits left turn 1;

I'm using:
Ubuntu 22.04;
gnu++23;
Vscode with c_cpp extension;

int main(int argc, char const *argv[])
{

    uint64_t mask1{1};
    uint64_t mask2{1};

    mask1 = 1 << 30; // OK 1000000000000000000000000000000
    mask2 = 1 << 31; // ERROR 1111111111111111111111111111111110000000000000000000000000000000
    // Expecting 10000000000000000000000000000000


    return 0;
}
康桓瑋
  • 33,481
  • 5
  • 40
  • 90

1 Answers1

1

In this line:

mask2 = 1 << 31;

First the expression on the right side is evaluated, and then assigned to mask2.
Since 1 is an int literal, the expression in evaluated as a 32 bit int.

Change it as following to achieve what you what:

mask2 = static_cast<uint64_t>(1) << 31;

It will perform the shift considering 1 as an unsigned 64 bit value.

Another option with a similar result is:

mask2 = 1ULL << 31;
wohlstad
  • 12,661
  • 10
  • 26
  • 39