I am trying to multiply two 16 bits numbers using the shift and add methods in assembly language and store the hi part in the dx register and the low part in the ax register. The multiplicand and multiplier are passed on the stack For some of my tests, I can get the right answer, but for some, the part that holds the higher part,dx, is wrong. For example if I do 0002 times 0001 I get in the my answer, dx = 0002 ax = 0002, when the answer should be dx = 0000 ax = 0002.
Here is my code. I can't seem to know where my code is going wrong. I even did this example by hand and don't see how the dx = 0002 part gets there.
;---------------------------------------
; Multiply data
;---------------------------------------
h dw 0 ; this holds the high order bits
mltplier dw 0 ; this holds the mulitplier
.code
;---------------------------------------
; Multiply code
;---------------------------------------
_multiply: ;
push bp ; save bp
mov bp,sp ; anchor bp into the stack
mov bx,[bp+4] ; load multiplicand from the stack
mov cx,[bp+6] ; load multiplier from the stack
mov [mltplier],cx ;
mov cx,0Fh ; make counter of 16
mov ax,0 ;
mov dx,0 ;
; calculate multiplicand * multiplier
; return result in dx:ax
_loop:
shr [mltplier],1 ; shift right by 1
jnc shift ; if the number shifted out was not a 1
;then we don't need to add anything
clc ;clear carry flag
add ax,bx ; add bx to ax, the low bits
add dx,[h] ; add var to dx, the high bits
shift: ;
shl [h],1 ; shift the high order bits left
shl bx,1 ; shift the low order bits left
adc [h],0 ; add to the high bits
clc ;clear carry flag
loop _loop ; loop the process
pop bp ; restore bp
ret ; return with result in dx:ax
;
end ; end source code
;---------------------------------------