This program is taken from the book Programming the Z80, the program is intended to do x-byte BCD subtraction, x could be any integer, and that's by counting the bytes of the two operands and executing the subtraction instruction consequentially through a loop, but here we will assume the two numbers have the same number of bytes, which we will call COUNT
. These numbers' addresses are N1
and N2
and the addresses that follow these. My question is in the code's comments.
BCDPAK LD B, COUNT
LD DE, N2
LD HL, N1
AND A ;Clear carry
MINUS LD A, (DE)
SBC A, (HL)
DAA ;Decimal adjust the result
LD (HL), A ;Store the result in HL
INC DE
INC HL ;Doesn't that overwrite the result?
DJNZ MINUS ;Decrement B, loop until B = 0
The result is stored at the address pointed to by HL, then HL (i.e. the pointer) is incremented to point to the next byte of the subtrahend and result.
Note that the result overwrites the subtrahend instead of the minuend which is normally what happens with most assembly instructions. E.g. SBC A, (HL)
will subtract (HL) from A and leave the result at A. However this routine will substract the number pointed to by HL from the one pointed to by DE and leave the result at the memory location originally pointed to by HL instead of DE