Using the PIC Subtract Instructions

The subtract instructions (SUBWF and SUBLW) on PICs work in a somewhat non-intuitive fashion as compared to typical 8-bit processors. The actual calculation performed by the PIC is (memory - W) rather than (W - memory).

For instance, if you want to subtract 3 from the W register, you might be tempted to write

but the actual effect of that instruction is to subtract W from 3.

The correct way to subtract a constant from W is to use the ADDLW instruction with an argument that is the two's complement of the desired subtrahend. For the example of subtracting 3 from W, you could use

	ADDLW	256-3
	ADDLW	253
or (in some assemblers)

The "backwardsness" of the SUBLW instruction can sometimes be put to good advantage. For example, to take the two's complement of the W register, you can use

rather than the perhaps more obvious sequence
	XORLW	0ffh
The same technique is useful for other complements, such as taking the 9's complement of a digit in W by
In general, any time it is necessary to reverse a sequence of numbers from A to B (where A and B are both in the range of 0 to 255), you can use
which will work even if the sum A+B is greater than 255.
Another thing to be aware of is that the carry bit as the result of a subtract instruction should be consider to be "NOT borrow" bit. In other words, if the subtraction would result in a borrow from a more significant byte, the carry flag will be clear. Otherwise it will be set. This behavior is the same as that of the 6502.
Back to my PIC Projects page
Back to my home page

Last updated July 21, 1995

Copyright 1995 Eric Smith