0

I found out that ~ is like a NOT operator because in binary, it changes all the 1 to 0 and all the 0 to 1. So, I explored what to do with this code, and I found this:

int x = 5;
System.out.println(~(x - 1)); // prints -5

But x in binary is 0101 and 4 is 0100. Using a NOT operator on 0100 creates 1011, which is 11. How is that -5?

TheXDShrimp
  • 127
  • 13

2 Answers2

1

int has 32 bits - you forgot about the other 28 bits that are set to 0, that ~ will turn into 1.

It's best to use Integer.toBinaryString for the visualization:

jshell> Integer.toBinaryString(~4)
$23 ==> "11111111111111111111111111111011"

As to why this value is -5:

Let's check what you get from ~4 + 4:

   11111111111111111111111111111011
 + 00000000000000000000000000000100
 ----------------------------------
   11111111111111111111111111111111

It's all ones! What happens if you now add 1?

   11111111111111111111111111111111
 +                                1
 ----------------------------------
   00000000000000000000000000000000

The computation overflows and you get 0!

Therefore: ~4 + 4 + 1 = 0. Put in another way, ~4 = -4 - 1 = -5.

Joni
  • 105,306
  • 12
  • 136
  • 187
0

~ is bitwise operator . inverts the bits of binary representation negative number are stored as 2's complement. binary representation of 5-1=4 is 0000 0100

now binary representation of 5 = 0000 0101 1's complement of 5 = 1111 1010 (invert the bits)

2's complement of 5 = 1111 1011 (add 1 to 1s complement) this is equal to ~5

so bitwise complement of 4 is ~5