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
>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.