This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade. View original topic
Borrow during subtracting operation (sbc)
by stenlik on 2016-12-11 (#184492)
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
Re: Borrow during subtracting operation (sbc)
by Kasumi on 2016-12-11 (#184495)
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.
Re: Borrow during subtracting operation (sbc)
by tokumaru on 2016-12-11 (#184507)
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)
by thefox on 2016-12-11 (#184524)
Internally, the subtraction is implemented by bitwise-inverting the second operand before addition.
So, addition is: (NOTE: result is 9 bits)
Code:
result := a + b + carry; carry := topmost bit of result;
Subtraction is: (NOTE: result is 9 bits. "~" is bitwise inversion, i.e. XOR the value by $FF)
Code:
result := a + ~b + carry; carry := topmost bit of result;
Re: Borrow during subtracting operation (sbc)
by stenlik on 2016-12-12 (#184599)