View Single Post
Old 8th May 2020, 11:53 am   #17
julie_m
Dekatron
 
Join Date: May 2008
Location: Derby, UK.
Posts: 7,732
Default Re: Wireless World calculator project

To perform the twos complement operation, as any fule kno, you flip the bits and add one.

In 8 bits, "flipping the bits" is equivalent to subtracting from 255; so flipping the bits and adding one is equivalent to subtracting from 256.

On the 6502 processor, the only difference between the ADC and SBC instructions is that SBC inverts each bit of the subtrahend/addend with a bunch of EOR gates as they are fed into the "B" input of the adder. So that takes care of flipping the bits. We still have to add one; but we can let the processor take care of that for us, by setting the carry flag with an SEC instruction before we start. Then we end up with A + (255 - B) + 1 = 256 + A - B. The excess of 256 means that if B is smaller than A, then the carry will be set, adding one also to the next more significant byte; if B is larger than A, the carry not being set borrows one.

(If you ever end up with the subtrahend already in the accumulator and need to evaluate something minus A, then you can use EOR #&FF, SEC and ADC..... it's only two extra bytes and two extra cycles.)
__________________
If I have seen further than others, it is because I was standing on a pile of failed experiments.
julie_m is offline