# java - Bitwise operator ~ giving the ouput not expected

• How does the bitwise complement (~) operator work?

``````0000 1010 // = 10 i.e binary representation of 10
1111 0101 // = ~10 i.e inversion of bits
``````

Negative numbers are stored in 2's complement form. Check this for details

``````0000 1011 // = 11 i.e binary 11
1111 0100 // inversion of bits
1111 0101 // 2's complement of 11 = -11
``````

Thus,

~10 = -11

If we look at the binary for the number 10 we can see

0000 0000 0000 0000 0000 0000 0000 1010

Where the first 0 is the signing bit.

If we now flip the binary INCLUDING the signing bit, we get:

1111 1111 1111 1111 1111 1111 1111 0101

Which... if you consider that java uses signed integers, is -11.

If we get away from signed numbers for a second and just consider the value of a 4-byte unsigned integer that is ~10 we get the value of: 4294967285.

To convert a unsigned integer to a two's complement signed integer we subtract the value of 2^32 from the integer if its over 2^31 - 1.

2^32 - 4294967285 = -11