为什么~2等于-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的补,我们可以通过将所有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位机器上。
我知道这个问题的答案很久以前就贴出来了,但我想分享我的答案。
要找到一个数的一补,首先要找到它的二进制等价物。这里,十进制数字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,带一个负号。你也可以用其他数字试试。
很简单:
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
这个操作是补语,不是否定语。
考虑~0 = -1,然后从这里开始。
否定的算法是,“补,加”。
你知道吗?还有一种“一的补”,它的逆数是对称的,它有一个0和一个-0。
简单地说,~就是找到对称值(到-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)。