Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unary complement (tilde ~) operator in Java

I just started learning programming in Java. I made a program which calculates the complement of an integer

package demo;

public class unaryOperators {
    public static void main(String[] args) {
        int numOne = 10;
        System.out.println(~numOne);
    }
}

The program runs without any errors but the output is not as expected! The output was -11 but as far as I know, Bitwise complement operator complements all the bits of the number.

10 in decimal is 1010

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, ~10 should be 0101 i.e. 5 in decimal!

I referred some articles but cannot find one which in simple for a novice like me to understand.

Thanks for your time!

>Solution :

Java integers are stored in two’s complement. Assuming (for simplicity) that we’re storing data in one byte, 10 is

00001010

so ~10 is

11110101

If the leading bit of a two’s complement number is 1, then the number is negative, and the exact value of that number is (the negative of) its complement plus one, hence -11. You can read the details of why this format is written the way it is in the linked Wikipedia page.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading