It follows from the definition of two's complement, -x = ~x + 1
If x
is negative: y = x>>31 = -1
. Rewrite the ~x
inversion as x ^ -1
, and the +1
to subtracting -1
, to get:
-x = (x ^ -1) - -1 = abs(x)
If x
is non-negative: y = 0
, and (x ^ 0) - 0)
is obviously just x
.