I am writing an NES emulator, and at its core is a 6502 processor without decimal mode.
I have written a 6502 core, and am using an NESTEST cartridge image to test the 6502 behaviour. The test cart comes with a log output of key processor parameters and the idea is, you generate your own log and compare it to the supplied log for accuracy.
BTW apologies in advance if I get my terminology wrong or switch between Hexadecimal and Decimal. I will try to be clear.
I have read up on the overflow or V flag and have written a function that sets or clears the V flag after each ADC or SBC.
Here's what I have surmised.
The V flag is set when the result of ADC or SBC overflows beyond 0x80 for negative numbers or 0x7f for positive.
For additions and subtractions with a positive and negative number, this should never happen (128 negative values, and 128 non negative values (Not sure if 0 is classed as positive)).
For additions and subtractions where the signs are alike, its possible to add two negative values and get a positive value, and vice versa and therefore when this happens, the overflow / V flag is set.
I have written a function and tested it with the example values on 6502.org V-Flag essay, and the V-Flag seems to work fine.
However, when I look at the NESTEST cart output, the V Flag seems to be set under other circumstances. See output log below.
Code: Select all
C94F 69 7F ADC #$7F A:7F X:00 Y:00 P:25 SP:FB PPU: 5, 50 CYC:585 ; ADC Immediate Accumulator and 0x7f + Carry Flag
C951 10 0B BPL $C95E A:FF X:00 Y:00 P:E4 SP:FB PPU: 5, 56 CYC:587 ; P now shows V flag as being set
with the example above, 0x7f is a positive number and 0x7f + carry is 0x80 , a negative number. This shouldn't come out as overflow.
In decimal its (+127) + (-128) = -1 or 0xff. The 0xff in the accumulator is correct, but the overflow flag has been set.
Can anyone explain why the V flag has been set in this case please?