0

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?

  • 2
    Does this answer your question? [What is “2's Complement”?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) – Michael Welch Oct 29 '20 at 02:41
  • Do you know how negative numbers are represented in two's complement? – Sweeper Oct 29 '20 at 02:42
  • 1
    Does `Integer.toBinaryString(int i)` help you understand? – Scary Wombat Oct 29 '20 at 02:42
  • 1
    If it is still not clear, try `System.out.println(Integer.toBinaryString(-1));` – Elliott Frisch Oct 29 '20 at 02:51
  • @Sweeper It is in 2's complement form, right? If yes then do tell me how positive numbers are stored. I guess in normal binary form? – Eric Kaiser Oct 29 '20 at 02:55
  • Eric, see the question I posted in my comment. It has several high quality answers to your question. The question is upvoted over 400 time and the answers have been upvoted hundreds of times. It doesn't get much better than that on stack overflow. – Michael Welch Oct 29 '20 at 02:56
  • Possibly in your manual calculation you did not take into account that an `int` has a *fixed* number of bits, but I'm just guessing here. – harold Oct 29 '20 at 03:01
  • @ScaryWombat Thank you. Just wanna clarify one thing that usually NOT operation is simply inversing of bits, right? Now 5 in binary is 00000101 then on reversing the bits it becomes 11111010. Now this is a negative number and Java stores negative numbers in 2's complement so we store it as 00000110 but the result is -6. On using your code I am getting that -6 is stored as 1010, why? Incase of -5, it gets stored as 11111011 and on doing the bitwise NOT operation it results in 00000100 which is 4. Since 00000100 is not a negative number it gets stored as it is. Also I know Java stores in 32bits. – Eric Kaiser Oct 29 '20 at 03:11

0 Answers0