为什么位移一个int向上产生负数? [英] Why does bit-shifting an int upwards produce a negative number?
问题描述
我是新来的位操作技巧和我写了一个简单的code看到在一个号码即做单位移位的输出。 2
I am new to bit manipulations tricks and I wrote a simple code to see the output of doing single bit shifts on a single number viz. 2
#include <iostream>
int main(int argc, char *argv[])
{
int num=2;
do
{
std::cout<<num<<std::endl;
num=num<<1;//Left shift by 1 bit.
} while (num!=0);
return 0;
}
此的输出如下。
The output of this is the following.
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位离开,会导致零它上面做,但为什么电脑输出负数的在最后的终止循环之前(因为NUM转身零)??
Obviously, continuously bit shifting to the left by 1 bit, will result in zero as it has done above, but why does the computer output a negative number at the very end before terminating the loop (since num turned zero)??
然而,当我把 INT NUM = 2
按无符号整数NUM = 2
然后我得到的输出不相同
这最后一个号码是这段时间显示为阳性,即 2147483648
而不是 -2147483648
However when I replace int num=2
by unsigned int num=2
then I get the same output except
that the last number is this time displayed as positive i.e. 2147483648
instead of -2147483648
我使用的是 GCC
编译器在Ubuntu Linux
I am using the gcc
compiler on Ubuntu Linux
推荐答案
这是因为 INT
是一个符号整数。在二进制补码再presentation ,整数的符号被确定最上面位。
That's because int
is a signed integer. In the two's-complement representation, the sign of the integer is determined by the upper-most bit.
一旦你已经转移了1到最高(符号)位,它翻转为负。
Once you have shifted the 1 into the highest (sign) bit, it flips negative.
当您使用无符号
,没有符号位。
When you use unsigned
, there's no sign bit.
0x80000000 = -2147483648 for a signed 32-bit integer.
0x80000000 = 2147483648 for an unsigned 32-bit integer.
编辑:
注意,严格来说,签署整数溢出在C / C未定义行为++。海湾合作委员会在这方面的行为是不完全一致:
Note that strictly speaking, signed integer overflow is undefined behavior in C/C++. The behavior of GCC in this aspect is not completely consistent:
-
NUM = NUM&LT;&LT; 1;
或NUM&LT;&LT; = 1;
通常作为上述行为 -
NUM + = NUM;
或NUM * = 2;
实际上可能的go插入GCC 一个无限循环。
num = num << 1;
ornum <<= 1;
usually behaves as described above.num += num;
ornum *= 2;
may actually go into an infinite loop on GCC.
这篇关于为什么位移一个int向上产生负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!