You are actually quite close.
In binary , not 0 should be 1
Yes, this is absolutely correct when we’re talking about one bit.
HOWEVER, an int whose value is 0 is actually 32 bits of all zeroes! ~ inverts all 32 zeroes to 32 ones.
System.out.println(Integer.toBinaryString(~0));
// prints "11111111111111111111111111111111"
This is the two’s complement representation of -1.
Similarly:
System.out.println(Integer.toBinaryString(~1));
// prints "11111111111111111111111111111110"
That is, for a 32-bit unsigned int in two’s complement representation, ~1 == -2.
Further reading:
- Two’s complement
- This is the system used by Java (among others) to represent signed numerical value in bits
- JLS 15.15.5 Bitwise complement operator
~- “note that, in all cases,
~xequals(-x)-1“
- “note that, in all cases,