[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Twos complement subtraction



roughana wrote:
I have a situation where I am modifying existing code that uses twos
complement subtraction in 65816 assembly.

Here's the original code:

TYA ; Length in Y
EOR #-1
SEC
ADC :PTRlength ;ZP address
STA :PTRlength ;ZPaddress

Now it turns out that we need to subtract one more than the length in
Y.
Here's one solution:

TYA
INC
EOR #-1
SEC
ADC :PTRlength ;ZP address
STA :PTRlength ;ZPaddress

and a second solution which is less cycles. But will this do the trick
in all cases?

TYA
EOR #-1
CLC
ADC :PTRlength ;ZP address
STA :PTRlength ;ZPaddress

I stepped through it and the second one worked with the case I tried.
Both resulted in carry set at the end.

I tried reading the theory behind this on Wikipedia
http://en.wikipedia.org/wiki/Two's_complement
which implied that carry should be set.
Is there a range of numbers for which clearing carry would be ok?

It's OK for all cases.

This is exactly equivalent to PTRlength = PTRlength - Y - 1.

In my case the routine is reducing the length of a Pstring.
The theoretical maximum length of a PString is 255 characters, however
the twos complement subtraction probably limits the maximum length to
127 characters. Using CLC instead of SEC could possibly limit the
maximum length even further... perhaps 64? I'm guessing now and would
like some input from someone who understands this better than I do.

I guess I can re-write the whole thing to be:

STY :TempLength ;ZPaddress
SEC
LDA :PTRlength ;ZP address
SBC :TempLength ;ZPaddress
STA :PTRlength ;ZPaddress

...which would then allow maximum length to be 255 again. This is
probably more readable and the code is not cycle critical anyway.

Definitely go the CLC route.  It produces the identical result
with no temp and fewer cycles.

-michael

NadaNet 3.1 for Apple II parallel computing!
Home page:  http://home.comcast.net/~mjmahon/

"The wastebasket is our most important design
tool--and it's seriously underused."