Because C integer types use a fixed number of bits, they are not the same as mathematical integers which are not bounded.
Since the carry bit out of the sign bit is discarded we can use bit operations to calculate the negative of an integer x.
The negative of a C x (e.g. of type int) is a C integer y (also type int in this case) such that
x + y = 0
That is, if x + y = 0, then y is -x.
How do we find such a y?
Easy!
-
First find an integer (z) such that
x + z = 0xFFFFFFFF
Answer: z = ~x;
-
But now, just add 1 since 0xFFFFFFFF + 1 is 0 (in C).
x + (~x + 1) = (x + ~x) + 1 = 0xFFFFFFFF + 1 = 0
So this shows that -x can be calculated using only ~ and + operators:
-x = ~x + 1