为什么~2等于-3?~操作符是如何工作的?
当前回答
我知道这个问题的答案很久以前就贴出来了,但我想分享我的答案。
要找到一个数的一补,首先要找到它的二进制等价物。这里,十进制数字2用二进制形式表示为0000 0010。现在通过将其二进制表示的所有数字逆(将所有1都翻转为0,将所有0都翻转为1)来求其1的补数,这将得到:
0000 0010 → 1111 1101
这是十进制数2的1补。由于二进制数的第一个位,即符号位为1,这意味着它存储的数字的符号为负。(这里所指的数字不是2,而是2的1的补数)。
现在,由于数字存储为2的补数(取1的补数加1),所以要将这个二进制数1111 1101显示为十进制,首先我们需要找到它的2的补数,即:
1111 1101 → 0000 0010 + 1 → 0000 0011
这是2的补。二进制数0000 0011的十进制表示是3。并且,因为符号位是1,所以结果是-3。
提示:如果你仔细阅读这个过程,你会发现1的补码操作符的结果实际上是,数字(操作数-,这个操作符被应用)加1,带一个负号。你也可以用其他数字试试。
其他回答
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
以上所有观点同时都是正确的。
正如其他人所提到的~只是翻转位(将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的链接
位操作符是一个一元操作符,根据我的经验和知识,它的工作原理是符号和幅度方法。
例如~2的结果是-3。
这是因为逐位操作符将首先以符号和幅度表示数字,即0000 0010(8位操作符),其中MSB是符号位。
然后取2的负数,也就是-2。
-2用符号和幅度表示为1000 0010(8位运算符)。
之后,它将1添加到LSB(1000 0010 + 1),得到1000 0011。
也就是-3。
这个操作是补语,不是否定语。
考虑~0 = -1,然后从这里开始。
否定的算法是,“补,加”。
你知道吗?还有一种“一的补”,它的逆数是对称的,它有一个0和一个-0。