简体   繁体   English

一元非运算符的内部工作(〜)

[英]Internal working of Unary Not Operator (~)

public class bitwise_operator {

    public static void main(String[] args) {

        int var1 = 42;
        int var2 = ~var1;
        System.out.println(var1 + " " + var2); 
   }
}

The above code produces 42 -43 as the output. 上面的代码产生42 -43作为输出。

As far as my understanding goes, Unary Not operator ( ~ ), inverts all of the bits of its operand. 据我所知, Unary Not运算符 )反转其操作数的所有位。

Now, 42 in binary is 00101010 . 现在,二进制4200101010 On using ~ operator, we get inverted value of 42 ie 11010101 使用 运算符时,我们得到反转值4211010101

If you convert the preceding binary value, the output should be something else and not -43 如果转换前面的二进制值,则输出应为其他值而不是-43

Tried my luck with different numbers to observe the pattern and found that, the output is 1 number more than the initial value supplied with a leading (-) sign before it, as seen in the above case. 用不同的数字试试我的运气来观察模式,发现输出比前面带有前导( - )符号的初始值 多1个数 ,如上例所示。

For eg.., 例如..,

if num is 45           // Output is 45 -46
if num is 1001        // Output is 1001 -1002

Could someone please explain how the Unary Not Operator (~) works internally to output such results? 有人可以解释一元非运算符(〜)如何在内部工作以输出这样的结果?

You are using a signed integer value which is in 2's complement. 您正在使用带符号的整数值,该值为2的补码。

Your result is correct: 11010101 is in fact -43: 你的结果是正确的:11010101实际上是-43:

-2^7 + 2^6 + 2^4 + 2^2 + 2^0 = -128 + 64 + 16 + 4 + 1 = -128 + 85 = -43 -2 ^ 7 + 2 ^ 6 + 2 ^ 4 + 2 ^ 2 + 2 ^ 0 = -128 + 64 + 16 + 4 + 1 = -128 + 85 = -43

This is what's known as two's complement, and it is how integers and all fixed point numbers in Java, C, C++ etc work 这就是所谓的二进制补码,它是Java,C,C ++等中的整数和所有定点数的工作方式。

-x = ~x + 1

So for example -1 (0xFFFF) negated bitwise (0x0) plus 1 = 0x1 所以例如-1(0xFFFF)否定按位(0x0)加1 = 0x1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM