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


当前回答

很简单:

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

其他回答

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

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

X = ~2

- (2 + 1)

-3

首先,我们必须把给定的数字分成它的二进制数,然后把它颠倒过来,把最后一个二进制数相加。执行完后,我们必须给我们正在寻找补数的前一位数字赋相反的符号 ~ 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。

简单地说,~就是找到对称值(到-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在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的补表示。

补运算符(~)只是翻转位。由机器来解释这些比特。