为什么~2等于-3?~操作符是如何工作的?
当前回答
基本上,动作是一种补充,而不是否定。
这里x= ~x产生的结果总是-(x+1)。
X = ~2
- (2 + 1)
-3
其他回答
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
以上所有观点同时都是正确的。
简单地说,~就是找到对称值(到-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)。
下面是一种解释:
让我们以~2 = -3为例(为了简单起见,使用8位系统进行解释)
1)我们有2——> 00000010
2)我们可以得到~2—> 11111101 #通过简单地交换位。
[但常见的错误是,有些人试图将~2的二进制值直接转换为十进制(以10为基数)数字,在这种情况下,它是253。这不是我们寻找互补的方式。
3)现在我们找到一个二进制数,将其与二进制值2~相加得到0(00000000)作为结果。 在这种情况下,它是00000011(即3),因为如果我们将00000011加到我们已有的11111101,我们得到100000000,但由于我们使用的是8位系统,1在第9位,它被完全忽略,所以我们最终得到00000000。
4)从点(3)我们可以说~2+3 = 0,因此我们可以说~2 = -3
注意:-3的值是简单的11111101,可以用同样的方式解释。
位操作符是一个一元操作符,根据我的经验和知识,它的工作原理是符号和幅度方法。
例如~2的结果是-3。
这是因为逐位操作符将首先以符号和幅度表示数字,即0000 0010(8位操作符),其中MSB是符号位。
然后取2的负数,也就是-2。
-2用符号和幅度表示为1000 0010(8位运算符)。
之后,它将1添加到LSB(1000 0010 + 1),得到1000 0011。
也就是-3。
正如其他人所提到的~只是翻转位(将1变为0,将0变为1),由于使用了2的补码,您就得到了您所看到的结果。
需要补充的一点是为什么使用2的补数,这是为了对负数的运算和对正数的运算是一样的。把-3看成是要加3才能得到0的数字,你会看到这个数字是1101,记住二进制加法就像小学(十进制)加法,只是你得到2时进1,而不是10。
1101 +
0011 // 3
=
10000
=
0000 // lose carry bit because integers have a constant number of bits.
因此1101是-3,翻转位就得到0010,也就是2。