Carry indicates
unsigned overflow
Overflow indicates
signed overflow.
When you figure that $81 can be -127 and $FF can be -1..
When adding two unsigned numbers results in > $FF, C is set
When adding two signed numbers results in > 127 ($7F) or < -128 ($80), V is set
In emulation, this can be easily checked by looking at the high bits. Basically:
Overflow is set if:
Positive + Positive = Negative
or
Negative + Negative = Positive
Overflow is cleared in all other instances.
Here's example code:
Code: Select all
// A = Accumulator before the addition
// v = the value adding to the accumulator
// s = the sum of the addition (A+v+C)
if( (A ^ s) & (v ^ s) & 0x80 )
Set_V();
else
Clear_V();
EDIT:
err... duh, you already posted example code.
Anyway as for how the code works...
Pos+Pos=Neg and Neg+Neg=Pos
Both conditions have the "sum" as the odd one out. So if the sign of the sum matches either the sign of A or the sign of v, then you don't overflow.
So in my example code:
All we're really interested in is the high bit... so ignore all the other bits in A,v,s.
A^s will have the high bit set if the signs mismatch
ditto for v^s
so... (A^s) & (v^s) ... the AND operation check to make sure both of those conditions had the high bit set (ie: s high bit didn't match A or v). If the AND results in the high bit set, the we know that we have overflow
The following & 0x80 just extracts the high bit.