1

Why is this code not giving expected value for n = 1000000000000 Expected value = 1099511627775 While the code is giving 255

long long now = n, count = 0, len = 0;
while (now >= 1) {
  count++;
  now /= 2;
}
len = (1 << count) - 1;
cout << len;
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

1 Answers1

7

In 1 << count the constant 1 is an int not a long long.
Then the shift overflows.
You should use 1ll << count.

prog-fh
  • 13,492
  • 1
  • 15
  • 30