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


当前回答

这个操作是补语,不是否定语。

考虑~0 = -1,然后从这里开始。

否定的算法是,“补,加”。

你知道吗?还有一种“一的补”,它的逆数是对称的,它有一个0和一个-0。

其他回答

~翻转值中的位。

为什么~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。

很简单:

Before starting please remember that 
 1  Positive numbers are represented directly into the memory.
 2. Whereas, negative numbers are stored in the form of 2's compliment.
 3. If MSB(Most Significant bit) is 1 then the number is negative otherwise number is 
    positive.

你会发现~2:

Step:1 Represent 2 in a binary format 
       We will get, 0000 0010
Step:2 Now we have to find ~2(means 1's compliment of 2)
                  1's compliment       
       0000 0010 =================> 1111 1101 

       So, ~2 === 1111 1101, Here MSB(Most significant Bit) is 1(means negative value). So, 
       In memory it will be represented as 2's compliment(To find 2's compliment first we 
       have to find 1's compliment and then add 1 to it.)
Step3:  Finding 2's compliment of ~2 i.e 1111 1101

                   1's compliment                   Adding 1 to it
        1111 1101 =====================> 0000 0010 =================> 0000 0010
                                                                      +       1
                                                                      ---------
                                                                      0000 0011 
        So, 2's compliment of 1111 1101, is 0000 0011 

Step4:  Converting back to decimal format.
                   binary format
        0000 0011 ==============> 3
        
       In step2: we have seen that the number is negative number so the final answer would  
       be -3
                                    
                                So, ~2 === -3

位操作符是一个一元操作符,根据我的经验和知识,它的工作原理是符号和幅度方法。

例如~2的结果是-3。

这是因为逐位操作符将首先以符号和幅度表示数字,即0000 0010(8位操作符),其中MSB是符号位。

然后取2的负数,也就是-2。

-2用符号和幅度表示为1000 0010(8位运算符)。

之后,它将1添加到LSB(1000 0010 + 1),得到1000 0011。

也就是-3。

基本上,动作是一种补充,而不是否定。

这里x= ~x产生的结果总是-(x+1)。

X = ~2

- (2 + 1)

-3