When the borrow (i.e. carry flag is cleared) happens during subtracting operation (sbc) on NES 6502? Is it each time the result is negative (-1 to -128)?
Many thanks!
Thanks
STeN
Borrow during subtracting operation (sbc)
Moderator: Moderators
Re: Borrow during subtracting operation (sbc)
The carry flag is cleared when the "true" result (as in, in normal subtraction) would have been less than zero. This is the only thing that matters.
For instance:
#$80-#$FF=#$81
This clears the carry because 128-255 is less than 0. It doesn't matter that the resulting byte #$81 happens to be negative.
#$01-#$FF= #$02
This clears the carry because 1-255 is less than 0. The resulting byte #$02 is positive, but that doesn't matter, because the normal result (-254) would have been negative.
The carry and the minus flag can give different results. carry is changed depending on if the result would have been outside the unsigned range of a byte, minus flag cares only about the highest bit of the resulting byte.
For instance:
#$80-#$FF=#$81
This clears the carry because 128-255 is less than 0. It doesn't matter that the resulting byte #$81 happens to be negative.
#$01-#$FF= #$02
This clears the carry because 1-255 is less than 0. The resulting byte #$02 is positive, but that doesn't matter, because the normal result (-254) would have been negative.
The carry and the minus flag can give different results. carry is changed depending on if the result would have been outside the unsigned range of a byte, minus flag cares only about the highest bit of the resulting byte.
Re: Borrow during subtracting operation (sbc)
In subtractions, I like to think of the carry flag as a 9th bit (i.e. with a value of 256) you put there just in case it's needed. It's not really part of the number, but as far as the CPU is concerned, it's subtracting from n + 256 instead of just n. If after the subtraction it's still there, it wasn't needed and there was no borrow, otherwise, there was a borrow.
Re: Borrow during subtracting operation (sbc)
Internally, the subtraction is implemented by bitwise-inverting the second operand before addition.
So, addition is: (NOTE: result is 9 bits)
Subtraction is: (NOTE: result is 9 bits. "~" is bitwise inversion, i.e. XOR the value by $FF)
So, addition is: (NOTE: result is 9 bits)
Code: Select all
result := a + b + carry;
carry := topmost bit of result;
Code: Select all
result := a + ~b + carry;
carry := topmost bit of result;
Download STREEMERZ for NES from fauxgame.com! — Some other stuff I've done: fo.aspekt.fi
Re: Borrow during subtracting operation (sbc)
Thanks all for comments.