0
votes

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?

1
How is 0b11111110 - 0b00000100 = 0b00000010? Ohhh, you're saying -252 is the same as +(-252). I think you have a typo then. The thing that confused me should be + not - in your post. - JohnFilleau
(Ignoring the typo in the sign) Why wouldn't it work? - Thomas Jager
If he two's complement of an 8 bit number, N is (256 - N). And if 8 bit addition and subtraction is modulo 256, that is N1 - N2 = (N1 - N2)%256. If you replace subtraction of N2 with addition of its twos complement, you get (N1 - N2) = (N1 + (256 - N2))%256. Modulo operation is distributive, and 256%256 = 0, so you find that for any values of N1 and N2, adding the two's complement of N2 is equivalent to subtracting N2. - JohnFilleau
@JohnFilleau indeed, that was a typo on my part. I'll correct it right away, sorry about that. - Carmo
@ThomasJager I mean, in my understanding, since most resources I found analyze two's complement numbers as signed, the operation wouldn't work with unsigned numbers beyond the range signed numbers are normally in. - Carmo

1 Answers

0
votes

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 is N1 - N2 = (N1 - N2)%256. If you replace subtraction of N2 with addition of its two's complement, you get (N1 - N2) = (N1 + (256 - N2))%256. Modulo operation is distributive, and 256%256 = 0, so you find that for any values of N1 and N2, adding the two's complement of N2 is equivalent to subtracting N2.

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.