Handling 16-bit Comparisons

It can be confusing enough in the 6502 to compare two single-byte values.  Trying to remember that BCC means "branch if less than" (assuming that the values were considered to be unsigned values from 0-255), and that BCS means "branch if greater than or equal to" is enough to saturate my memory banks.  I finally made a note on a card and tacked it up over my computer.  Of course, if the values are considered to be signed values, in the range of -128 through +127, the problem is compounded, to say the least.

But what about comparing two values of two-bytes each?  Like comparing two address pointers, for instance?  A last resort would be to subtract one from the other, in two-byte arithmetic, and then compare the difference to zero.  At least that would be understandable!  But let's try to do it a little better than that.  There is an example of this kind of comparison in lines 1310 through 1350 of the PRETTY.LIST program elsewhere in this issue of the Apple Assembly Line.  Here is the segment:

    1310 .1    LDA SCRP
    1320       CMP HIMEM
    1330       LDA SRCP+1
    1340       SBC HIMEM+1
    1350       BCS .2

The object is to determine whether the value in PP,PP+1 is still less than the value in HIMEM,HIMEM+1 or not.  The low-order byte of each value is stored in the first byte of each byte-pair, and the high-order byte is stored in the second byte.  If all we needed to compare was the low-order bytes, we could do it with lines 1310 and 1320 above.  Carry would be cleared by the CMP instruction if (SCRP) was less than (HIMEM).  (I have just started using "(" and ")" to mean "the value stored in".)

Now let's use that carry bit and continue the comparison by actually subtracting the two high-order bytes.  If the result of the subtraction leaves carry clear, we know that (SCRP) is indeed less tha (HIMEM), all 16 bits of it.

If you need to extend this to more than two bytes per value, you may.  Just insert a pair of LDA-SBC instructions for each extra byte of precision, before the BCS instruction.

For another example of this kind of comparison, you might look up the NXTA1 routine in the Apple Monitor listing, at $FCBA.  This routine is used by the Monitor MOVE command, and several other routines.
