Code: Select all
; Multiply the 16-bit value in A:X by the 16-bit value in Y:B and store the result in A:X
; Input: A:X = first operand
; Y:B = second operand
; Output: A:X = product
; Y:B = undefined
multiply:
ldy #0 ; Clear Y register
sta temp_low ; Save low byte of first operand
sty temp_high ; Save high byte of first operand
stx temp_low+1 ; Save low byte of second operand
stx temp_high+1 ; Save high byte of second operand
lda #0 ; Clear A register
ldx #0 ; Clear X register
loop:
lsr temp_low+1 ; Shift right second operand
ror temp_high+1 ; Rotate through carry second operand
bcc skip ; Skip add if carry is clear
clc ; Clear carry flag
lda temp_low ; Add first operand to A
adc temp_low+1 ; Add second operand to A
sta temp_low ; Save result
ldx temp_high ; Add first operand to X
adc temp_high+1 ; Add second operand to X
stx temp_high ; Save result
skip:
inx ; Increment X register
bne loop ; Repeat until X overflows
lda temp_low ; Load result low byte
ldx temp_high ; Load result high byte
rts ; Return from subroutine
temp_low: .byte 0 ; Temporary storage for low byte of first operand
temp_high: .byte 0 ; Temporary storage for high byte of first operand