[英]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.
我也使用 long long 来防止溢出。
Code代码
#include <iostream>
using namespace std;
int main() {
for(long long i=0;i<64;i++){
cout << 1LL*(1<<i) << " ";
}
return 0;
}
Output 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
. ..在上面的行中,
1
是一个int
而 i 是一个long long
。 So to fix your issue you can cast to a long long
as such:因此,要解决您的问题,您可以
long long
使用:
#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.这将允许您将 go 设置为更高的值。
You can also use 1LL
( 1 long long
) instead of casting:您还可以使用
1LL
( 1 long long
) 而不是强制转换:
cout << 1LL * (1LL << i) << " ";
..with this you can remove 1LL *
: ..有了这个你可以删除
1LL *
:
cout << (1LL << i) << " "; // Brakcets are required
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.