## Re: [stella] time to stick me with a fork?

 Subject: Re: [stella] time to stick me with a fork? From: Chris Wilkson Date: Sun, 14 Mar 2004 18:19:24 -0500 (EST)
```On 14 Mar 2004 KirkIsrael@xxxxxxxxxxxxx wrote:

> I know that's a rough, vaguely handwaving description that
> misses the "why" (like, I think there's a more elegant, deeper
> reason why they didn't reverse the meaning, so you always
> Cleared Carry before any math) but I'm getting the basics.

The carry bit serves the same purpose in both operations, but in reverse
of each other.

For addition, the carry bit signals an overflow.  When set it means the current
byte has overflowed and you need to increment the next-most-significant byte
to compensate.

For subtraction, the carry bit signals an underflow....you subtracted a big
number from a small number and the result is less than zero.  So you need to
borrow 1 from the next-most-significant byte to compensate.  Think of the
carry as a "borrow" bit when subtracting.

Now, the reason you have to set the carry to a 1 for subtraction is because
of 1's complement vs. 2's complement.  There are no circuits to subtract in
the 6502.  The way it does subtraction is by adding the 1's complement of
the accumulator and then adding 1 to give the result in 2's complement.  We
expect to see 2's complement.

the sbc instruction can be thought of like this:

sbc m      ; m EOR %11111111  (step 1: complement operand)
; a <- a + m + C        (step 2: adc m)

Example: assume a=7, m=5

what we see and do: 7-5=2

what the 6502 sees:  a = %00000111
m = %00000101
C = (something)

what the 6502 does:  %00000111 + %11111010 + C = %00000001 (=1 if C=0)
%00000111 + %11111010 + C = %00000010 (=2 if C=1)

This also works for signed numbers:

what we write: 7-(-5)=12
what the 6502 sees:  a = %00000111
m = %11111011
C = (something)

what the 6502 does:  %00000111 + %00000100 + C = %00001011 (=11 if C=0)
%00000111 + %00000100 + C = %00001100 (=12 if C=1)

I remember when I tried to comprehend the setting the C bit to subtract.
It hurt a lot.  But when I sat down and thought about the way the sbc