I was trying to understand bitwise NOT operator in Java.
On running the below code, I am getting the output as -6.
class Test {
public static void main (String[] args) {
int x = 5;
System.out.println(~x);
}
}
And on running this one I am getting the output as 4.
class Test {
public static void main (String[] args) {
int x = -5;
System.out.println(~x);
}
}
I have searched on Google about this and learnt that numbers are stored as 2's complement in Java but I really can't figure it out how we are arriving at the above results. I know that to find 2's complement I need to convert the number to binary format and then have to do a 1's complement which is just inverse of the bits and then add 1 to the 1's complement but on paper I am not getting those outputs as displayed by the program. I can't figure out where I am going wrong.
Can you help me out to understand this concept?