Reputation: 455
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?
Upvotes: 1
Views: 871
Reputation: 35011
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
-x = ~x + 1
So for example -1 (0xFFFF) negated bitwise (0x0) plus 1 = 0x1
Upvotes: 0
Reputation: 3688
You are using a signed integer value which is in 2's complement.
Your result is correct: 11010101 is in fact -43:
-2^7 + 2^6 + 2^4 + 2^2 + 2^0 = -128 + 64 + 16 + 4 + 1 = -128 + 85 = -43
Upvotes: 3