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.
As far as my understanding goes, Unary Not operator (~), inverts all of the bits of its operand.
Now, 42 in binary is 00101010. On using ~ operator, we get inverted value of 42 i.e. 11010101
If you convert the preceding binary value, the output should be something else and not -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.
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?