简体   繁体   中英

C++ Left Shift Operation Bit Manipulation

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 
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM