为什么~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的二进制表示。
记住,负数被存储为正数的补数。作为一个例子,这里是-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的补表示。
补运算符(~)只是翻转位。由机器来解释这些比特。
简单的 ...........
作为任何数字的2的补,我们可以通过将所有1逆为0来计算,反之亦然,然后再加上1。
这里N= ~N产生的结果总是-(N+1)。因为系统以2的补码的形式存储数据,这意味着它像这样存储~N。
~N = -(~(~N)+1) =-(N+1).
例如::
N = 10 = 1010
Than ~N = 0101
so ~(~N) = 1010
so ~(~N) +1 = 1011
点就是负的原点。我的观点是假设我们有32位寄存器,这意味着2^31 -1位涉及到操作,剩下的一位在早期计算(补码)中被存储为符号位,通常为1。结果是~10 = -11。
~(-11) =10;
如果printf("%d",~0);结果是-1;
但printf(“%u”,~0)比结果:4294967295在32位机器上。
正如其他人所提到的~只是翻转位(将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。
int = 4; System.out.println (~); 结果是:-5
Java中任意整数的“~”表示1对no的补。 例如,我取~4,这意味着用二进制表示0100。 首先, 整数长度为4字节,i。e4 *8(8位1字节)=32。 在系统内存中,4表示为 0000 0000 0000 0000 0000 0000 0000 0100 现在~操作符将对上面的二进制no执行1的补
i.e 1111 1111 1111 1111 1111 1111 1111 1011->1's complement the most significant bit represents sign of the no(either - or +) if it is 1 then sign is '-' if it is 0 then sign is '+' as per this our result is a negative number, in java the negative numbers are stored in 2's complement form, the acquired result we have to convert into 2's complement( first perform 1's complement and just add 1 to 1's complement). all the one will become zeros,except most significant bit 1(which is our sign representation of the number,that means for remaining 31 bits 1111 1111 1111 1111 1111 1111 1111 1011 (acquired result of ~ operator) 1000 0000 0000 0000 0000 0000 0000 0100 (1's complement)
1(2的补数)
1000000 0000 0000 0000 0000 0000 0000 0101 现在结果是-5 查看视频<[java中的位运算符]https://youtu.be/w4pJ4cGWe9Y的链接