Search code examples
assemblyx86masminteger-overfloweflags

Explanation of setting the overflow flag


In Kip Irvine's book he talks about the mechanism to set the overflow flag, he writes:

The CPU uses an interesting mechanism to determine the state of the Overflow flag after an addition or subtraction operation. The Carry flag is exclusive ORed with the high bit of the result. The resulting value is placed in the Overflow flag.

I wrote a simple program that shows that adding 5 to 127 in the al register sets the overflow flag :

0111 1111 + 0000 0101 = 1000 0100 carry flag = 0, high bit = 1, overflow = 1

However adding 5 to 255 in the al register does not set the overflow flag:

1111 1111 + 0000 0101 = 0000 0100 carry flag = 1, high bit = 0, overflow = 0

Why isn't the overflow flag set in the second example isn't the conditional statement satisfied ie; carry flag = 1 and high bit = 0?


Solution

  • The reason why the overflow flag is not set in your second example 255 + 5 is because it is concerned with signed arithmetic. You are adding -1 + 5 which gives 4. There is no overflow: the result is correct. As @Jester commented, there must be a mistake in your book.

    My 8086 book says of the Overflow flag:

    It will be set if there is an internal carry from bit 6 to bit 7 (the sign bit) and there is no external Carry. It will also be set when there is no internal carry from bit 6 to bit 7 and there is an external Carry.

    EDIT

    The paragraph continues:

    For the technically minded reader, the overflow flag is set by XOR-ing the carry-in and the carry-out of bit 7 (the sign bit).

    In the second example, 1 is carried out (to the Carry flag), and because all the bits were set, there must have been an internal carry-in during the internal addition, even if the resultant b7 is 0.