Why is it that ~2 is equal to -3? How does ~
operator work?
Simply ...........
As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..
Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.
~N = -(~(~N)+1) =-(N+1).
For example::
N = 10 = 1010
Than ~N = 0101
so ~(~N) = 1010
so ~(~N) +1 = 1011
Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.
~(-11) =10 ;
The above is true if printf("%d",~0); we get result: -1;
But printf("%u",~0) than result: 4294967295 on 32 bit machine.