相关疑难解决方法(0)

为什么向上移位int会产生负数?

我是位操作技巧的新手,我写了一个简单的代码来查看在单个数字上进行单个位移的输出. 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;
}
Run Code Online (Sandbox Code Playgroud)

输出如下.

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
Run Code Online (Sandbox Code Playgroud)

显然,连续比特移位到左边由1个比特,将导致零,因为它已经在上面进行,但为什么计算机输出一个负数在最后终止在循环之前(自NUM接通零)??

然而,当我替换时int num=2,unsigned int num=2我获得相同的输出,除了最后一个数字是这个时间显示为正,2147483648而不是-2147483648

gcc在Ubuntu Linux上使用编译器

c c++ bit-manipulation bit-shift

7
推荐指数
1
解决办法
2588
查看次数

标签 统计

bit-manipulation ×1

bit-shift ×1

c ×1

c++ ×1