They're doing unsigned 5-bit binary, and the result is 5-bit
That's the same binary operation as two's complement, only the interpretation of the values represented by the bit-patterns is different.
22
is 10110
, 13 is 01101
. We know its unsigned because the leading bit is 1
, but it's 22
not -10
.
To do 22-13
, they're forming ~13 + 1
= 10010 + 1
= 10011
separately in the diagram on the lest, unlike a binary adder-subtractor would. (It would do the +1 as carry-in to a single addition operation1.) The diagram on the right doesn't pre-add the +1
.
(That 10011
bit-pattern doesn't necessarily have a meaning as positive or negative number, unless you had zero-extended to at least 6-bit to make the starting numbers all signed-positive. For example, 13-22
would involve 01101 + (01001 + 1)
.)
Then they add. The carry-out = 1 from addition means there was no borrow. That's why some ISAs like ARM use their carry flag as a not-borrow after subtraction, so they can use that ALU result directly. Instead of inverting it like x86 does so CF=0
means no borrow after cmp or sub, that the subtraction didn't wrap around, because 22U >= 13U
.
So it's not correct to call this an overflow in the subtraction. 22 - 13
is mathematically in the 0..31 range, it doesn't need to wrap to stay in that range.
The fact that the add overflowed means that the subtraction didn't. Hopefully that's what the textbook meant or was trying to say.
This can't be 5-bit 2's complement, because the 22
input isn't in the -16..+15
range in the first place. But if you were doing signed 2's complement, signed overflow is a different condition. Unsigned overflow just detects zero-crossing. Unsigned overflow would be something like -9 - 8
which is mathematically -17
, in 5-bit 2's complement would wrap to 15. (Overflow in signed subtraction can only happen when the inputs are opposite-sign numbers.)
Footnote 1: it must be a single add-with-carry, not ~y+1
and then add
Note that doing only a single add operation with carry-in is essential for the carry-out to actually be meaningful in all cases. If you did 22 - 0
by first doing 11111 + 1
= 0, then 22 + 0
produce a carry-out of 0. But that's wrong, that would mean that 22U >= 0
is false.
If you do it the way a hardware adder-subtractor would, as 22 + 0b11111
with carry-in of 1
, then 22 - 0
does still wrap back to 22
, but with carry-out = 1
from the add-with-carry.