From a negative decimal to 2's complement, first ignore the sign and get the binary representation, then flip all the bits and add one.
From a negative 2's complement to decimal, flip all the bits and add one, and then convert the binary to decimal.
I feel it almost says that the operation duo (flip bits, add one) is applying a minus sign, and if I apply it twice, it is the same number. According to this answer, by observation, x + ~x = -1
, so -x = ~x + 1
. So I think it makes sense.
However, intuitively for the second conversion above, I would do the reverse of the first conversion: subtract one and then flip all the bits, as I would do (unsigned binary) = ~(2's complement - 1)
, given the equation (2's complement) = ~(unsigned binary) + 1
.
And yes, it seems that the duo (subtract one, flip bits) also works for the conversion between 2's complement and decimal. If it is true, my questions are:
- what is the idea behind this duo?
- why are there two duo operations that can do the conversion?
- why do we prefer the duo (flip bits, add one)?
Thank you!