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

Why is the 1's complement of decimal 10 printed as -11 in Java?

int n = 10;
int n1 = ~n;

System.out.println(Integer.toBinaryString(n)); // 1010 but, maybe 00000000 00000000 00000000 00001010
System.out.println(n); // 10
System.out.println(Integer.toBinaryString(n1)); // 11111111111111111111111111110101
System.out.println(n1); // -11

How does 11111111111111111111111111110101 output as -11?

I couldn’t find a way to convert the complement back to decimal

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

>Solution :

The two’s complement is used for negative numbers

-n = ~n + 1
  • -0 (-0…0000) = 1…1111 + 1 = 0…0000
  • -1 (-0…0001) = 1…1110 + 1 = 1…1111
  • -2 (-0…0010) = 1…1101 + 1 = 1…1110
  • -10 (-0…1010) = 1…0101 + 1 = 1…0110

Your miscomprehension is that the ~ operator makes a bit "negative." It just is the one’s complement, bitwise negate.

1...0110 (-10)
0...1010 (+10)
-------- +
      :0
     C0       C=carry
    C0
...C0
--------
0...0000 (0)
========

As ~n = -n -1, ~10 = -10 – 1 = -11.
Just as ~0 = -0 – 1 = -1.


Array.binarySearch(array, searchKey) uses the one’s complement, ~. It gives a non-negative index of the key when found, and the ones complement (hence negative) for the insert position when the key was not found. A result of -1 means insert position 0, before the first element in the array.

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