Reputation: 115
I was reading on two's complement recently and noticed that, when working with unsigned integers very close to the limit (mostly numbers large enough that the MSB is 1), subtraction seems to still work, even when the signed bit should still be filled with actual number information. For example, take 254 and 252, represented as 0b11111110
and 0b11111100
in 8-bits respectively. Subtraction would take the 2's complement of 252, so it's 0b11111110 + 0b00000100
which gives the correct result 0b00000010 = 2
. Why exactly does this work as intended?
PS.: I did also notice that if I were to take the unsigned numbers and look at them as if they were in the two's complement form, I'd get -2 and -4, which do subtract to 2. Is this perhaps a consequence of how the system was established and ended up being used by design?
Upvotes: 0
Views: 291
Reputation: 115
Following John Filleau's comment:
If the two's complement of an 8 bit number
N
is(256 - N)
, and if 8 bit addition and subtraction is modulo 256, that isN1 - N2 = (N1 - N2)%256
. If you replace subtraction ofN2
with addition of its two's complement, you get(N1 - N2) = (N1 + (256 - N2))%256
. Modulo operation is distributive, and256%256 = 0
, so you find that for any values of N1 and N2, adding the two's complement ofN2
is equivalent to subtractingN2
.
My main mistake in analyzing this operation was (aside from overlooking the fact that the values wrap) assuming that the computer would need to convert unsigned ints into signed ints to perform subtraction operations, which, as shown above, is not necessarily the case. The idea of the complement works in both unsigned and signed numbers.
Upvotes: 0