public mpy16
; This routine multiplies the 16-bit values in DE and HL and returns the
; 32-bit result in HLBC (HL has high 16 bits; BC has low 16 bits). Register
; pair AF is preserved.
mpy16:
ex af,af' ; Save AF
ld a,h ; Transfer factor in HL to A and C
ld c,l
ld hl,0 ; Initialize product
ld b,16 ; Set bit counter
rra ; Shift AC right so first multiplier bit
rr c ; ..is in carry flag
mp161:
jr nc,mp162 ; If carry not set, skip the addition
add hl,de ; Add multiplicand
mp162:
rr h ; Rotate HL right, low bit into carry
rr l
rra ; Continue rotating through AC, with
rr c ; ..next multiplier bit moving into carry
djnz mp161 ; Loop through 16 bits
ld b,a ; Move A to B so result is in HLBC
ex af,af' ; Restore original AF registers
ret
end