为什么~2等于-3?~操作符是如何工作的?
当前回答
基本上,动作是一种补充,而不是否定。
这里x= ~x产生的结果总是-(x+1)。
X = ~2
- (2 + 1)
-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
这里,二进制(8位)中的2是00000010,它的1的补码是11111101, 1的补数减去1得到1111110 -1 = 11111100, 这里的符号是-作为第8个字符(从R到L)是1 求1的补,no。即00000011 = 3 符号是负的所以这里是-3。
位操作符是一个一元操作符,根据我的经验和知识,它的工作原理是符号和幅度方法。
例如~2的结果是-3。
这是因为逐位操作符将首先以符号和幅度表示数字,即0000 0010(8位操作符),其中MSB是符号位。
然后取2的负数,也就是-2。
-2用符号和幅度表示为1000 0010(8位运算符)。
之后,它将1添加到LSB(1000 0010 + 1),得到1000 0011。
也就是-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位机器上。
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的链接