Home > database >  C Left Shift Operation Bit Manipulation
C Left Shift Operation Bit Manipulation

Time:02-28

I am not able to get why it is giving negative after certain point. Also I am using long long to prevent overflow.

Code

#include <iostream>
using namespace std;

int main() {
    
    for(long long i=0;i<64;i  ){
        cout << 1LL*(1<<i) << " ";
    }
    
    return 0;
}

Output

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 

CodePudding user response:

1 << i

..in the above line, 1 is an int and i is a long long. So to fix your issue you can cast to a long long as such:

#include <iostream>
using namespace std;

int main() {

    for (long long i = 0; i < 64; i  ) {
        cout << 1LL * (static_cast<long long>(1) << i) << " ";
    }

    return 0;
}

This will allow you to go to higher values.

You can also use 1LL (1 long long) instead of casting:

cout << 1LL * (1LL << i) << " ";

..with this you can remove 1LL *:

cout << (1LL << i) << " "; // Brakcets are required
  • Related