Borrow during subtracting operation (sbc)

Are you new to 6502, NES, or even programming in general? Post any of your questions here. Remember - the only dumb question is the question that remains unasked.

Moderator: Moderators

Post Reply
stenlik
Posts: 3
Joined: Sun Dec 11, 2016 1:43 am

Borrow during subtracting operation (sbc)

Post by stenlik »

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
User avatar
Kasumi
Posts: 1293
Joined: Wed Apr 02, 2008 2:09 pm

Re: Borrow during subtracting operation (sbc)

Post by Kasumi »

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.
User avatar
tokumaru
Posts: 12427
Joined: Sat Feb 12, 2005 9:43 pm
Location: Rio de Janeiro - Brazil

Re: Borrow during subtracting operation (sbc)

Post by tokumaru »

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.
User avatar
thefox
Posts: 3134
Joined: Mon Jan 03, 2005 10:36 am
Location: 🇫🇮
Contact:

Re: Borrow during subtracting operation (sbc)

Post by thefox »

Internally, the subtraction is implemented by bitwise-inverting the second operand before addition.

So, addition is: (NOTE: result is 9 bits)

Code: Select all

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: 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
stenlik
Posts: 3
Joined: Sun Dec 11, 2016 1:43 am

Re: Borrow during subtracting operation (sbc)

Post by stenlik »

Thanks all for comments.
Post Reply