bitwise not operator

Sawyer picture Sawyer · Mar 25, 2010 · Viewed 51.9k times · Source

Why bitwise operation (~0); prints -1 ? In binary , not 0 should be 1 . why ?

Answer

polygenelubricants picture polygenelubricants · Mar 25, 2010

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: