按位不运算如何给出负值

jin*_*imo 3 c++ bit-manipulation bitwise-not

我想通过一个简单的例子来看看按位不工作是如何工作的:

int x = 4;
int y;
int z;
y = ~(x<<1);
z =~(0x01<<1);
cout<<"y = "<<y<<endl;
cout<<"z = "<<z<<endl;
Run Code Online (Sandbox Code Playgroud)

这导致y = -9z = -3。我不明白这是怎么发生的。任何人都可以教育我一点吗?

GBl*_*ett 6

(x<<1) 会将位移一,所以

00000000 00000000 00000000 00000100
Run Code Online (Sandbox Code Playgroud)

会变成:

00000000 00000000 00000000 00001000
Run Code Online (Sandbox Code Playgroud)

这是 的表示8。然后~将反转所有位,使其变为:

11111111 11111111 11111111 11110111
Run Code Online (Sandbox Code Playgroud)

这是 的表示-9


0x01

00000000 00000000 00000000 00000001
Run Code Online (Sandbox Code Playgroud)

以二进制形式,因此当移位一次时变为:

00000000 00000000 00000000 00000010
Run Code Online (Sandbox Code Playgroud)

然后什么时候~应用我们得到:

11111111 11111111 11111111 11111101
Run Code Online (Sandbox Code Playgroud)

哪个是-3二进制的

  • 负数通常使用 [二进制补码](https://en.wikipedia.org/wiki/Two's_complement) 而不是符号大小来表示,您可以在其中取正数版本的按位非,然后加一它。因此,幅度较小的负数由一堆 1 表示。 (4认同)
  • @jingweimo 最高位(第一位)决定它是正数还是负数。如果第一位为1,则为负,如果为0,则为正 (2认同)