HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Two's complement addition

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
complementtwoaddition

Problem

I am currently learning about a CPU's status register and was confused about the difference between the carry flag and the overflow flag. Then I found article [1] which explains it very well, but I stumbled across one paragraph I don't really understand:


The rules for two's complement detect errors by examining the sign of
the result. A negative and positive added together cannot be wrong,
because the sum is between the addends. Since both of the addends fit
within the allowable range of numbers, and their sum is between them, it
must fit as well. Mixed-sign addition never turns on the overflow flag.

Let's look at 1111 and 0111. Both are valid 4-bit two's component values with a different sign. If I add them, I the carry-flag is turned on because the result of this addition is a 5-bit value.

The author says that errors in twos complement calculations can be found just by looking at the overflow bit. The overflow bit in this example would not get turned on, but in my opinion, this is an error. Why does the author claim this then? Why does the author tell the reader multiple times to ignore the carry bit when doing twos complement calculations?

[1] http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Solution

If you perform the addition, you get 1111+0111 = 0110 (ignoring the carry bit). In decimal, this reads $-1 + 7 = 6$, which is indeed correct. There is no error.

You can check that when adding a positive number and a negative number, if the result is non-negative then there will always be carry, which can be safely ignored.

Context

StackExchange Computer Science Q#86287, answer score: 4

Revisions (0)

No revisions yet.