为什么~2等于-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 

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

其他回答

~翻转值中的位。

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

2是二进制值

00000010

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

11111101

它是-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。

首先,我们必须把给定的数字分成它的二进制数,然后把它颠倒过来,把最后一个二进制数相加。执行完后,我们必须给我们正在寻找补数的前一位数字赋相反的符号 ~ 2 = 3 解释: 2的二进制形式是00000010变成11111101,这是1的补码,然后补码为00000010+1=00000011,这是3的二进制形式,带-符号,即-3

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


位补操作符(~)是一个一元操作符。

它的工作原理如下

首先,它将给定的十进制数转换为相应的二进制数 价值。这是在2的情况下,它首先将2转换为0000 0010(到8位二进制数)。

然后它将数字中的所有1都转换为0,所有0都转换为1,然后数字将变成11111101。

这是-3的2的补表示。

为了找到无符号的值使用补,即。要简单地将1111 1101转换为十进制(=4294967293),只需在打印时使用%u。