为什么~2等于-3?~操作符是如何工作的?
当前回答
~翻转值中的位。
为什么~2等于-3与数字的位表示方式有关。数字用二的补数表示。
2是二进制值
00000010
和~2翻转位,所以现在的值是:
11111101
它是-3的二进制表示。
其他回答
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
以上所有观点同时都是正确的。
这里,二进制(8位)中的2是00000010,它的1的补码是11111101, 1的补数减去1得到1111110 -1 = 11111100, 这里的符号是-作为第8个字符(从R到L)是1 求1的补,no。即00000011 = 3 符号是负的所以这里是-3。
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的链接
我认为对于大多数人来说,困惑的部分来自于十进制数和有符号二进制数的区别,所以让我们先澄清一下:
对于人类十进制世界: 01表示1, -01表示-1, 对于计算机的二进制世界: 101是无符号的,表示5。 101的意思是(-4 + 1),如果是有符号的数字在x位置。 | x
所以2的翻转位= ~2 = ~(010)= 101 = -4 + 1 = -3 这种混淆是由于混淆了有符号的结果(101=-3)和没有符号的结果(101=5)
基本上,动作是一种补充,而不是否定。
这里x= ~x产生的结果总是-(x+1)。
X = ~2
- (2 + 1)
-3