为什么~2等于-3?~操作符是如何工作的?


当前回答

简单地说,~就是找到对称值(到-0.5)。

~a和a应该与0和-1中间的镜像对称。

- 5, 4, 3, 2, 1 | 0, 1, 2, 3, 4

~0 == -1
~1 == -2
~2 == -3
~3 == -4

这是因为计算机是如何表示负数的。

比如说,如果正值用1来计数,负值就用0。

1111 1111 == -1

1111 1110 == -2; // add one more '0' to '1111 1111'

1111 1101 == -3; // add one more '0' to '1111 1110'

最后,~i == -(i+1)。

其他回答

这里,二进制(8位)中的2是00000010,它的1的补码是11111101, 1的补数减去1得到1111110 -1 = 11111100, 这里的符号是-作为第8个字符(从R到L)是1 求1的补,no。即00000011 = 3 符号是负的所以这里是-3。

~翻转值中的位。

为什么~2等于-3与数字的位表示方式有关。数字用二的补数表示。

2是二进制值

00000010

和~2翻转位,所以现在的值是:

11111101

它是-3的二进制表示。

记住,负数被存储为正数的补数。作为一个例子,这里是-2在2的补码中的表示:(8位)

1111 1110

得到它的方法是取一个数字的二进制表示,取它的补位(所有位的倒数),然后加1。Two从0000 0010开始,通过反转位,我们得到1111 1101。加1得到上面的结果。第一个位是符号位,表示负号。

那么让我们看看如何得到~2 = -3:

这里还有两个:

0000 0010

简单地翻转所有的位,我们得到:

1111 1101

那么-3在2的补中是什么样的呢?从正3,0000 0011开始,将所有位翻转到1111 1100,并添加1位成为负值(-3),1111 1101。

所以如果你简单地将2中的位反转,你就得到了2的-3的补表示。

补运算符(~)只是翻转位。由机器来解释这些比特。

我认为对于大多数人来说,困惑的部分来自于十进制数和有符号二进制数的区别,所以让我们先澄清一下:

对于人类十进制世界: 01表示1, -01表示-1, 对于计算机的二进制世界: 101是无符号的,表示5。 101的意思是(-4 + 1),如果是有符号的数字在x位置。 | x

所以2的翻转位= ~2 = ~(010)= 101 = -4 + 1 = -3 这种混淆是由于混淆了有符号的结果(101=-3)和没有符号的结果(101=5)

Javascript波浪号(~)将给定值强制转换为1的补位——所有位都是反向的。 这就是波浪的作用。这不是固执己见。它既不加也不减任何量。

0 -> 1
1 -> 0
...in every bit position [0...integer nbr of bits - 1]

On standard desktop processors using high-level languages like JavaScript, BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.

JavaScript Tilde operation (1's complement)

BASE2 lens
~0001 -> 1110  - end result of ~ bitwise operation

BASE10 Signed lens (typical JS implementation)
~1  -> -2 

BASE10 Unsigned lens 
~1  -> 14 

以上所有观点同时都是正确的。