【发布时间】:2016-01-24 01:26:40
【问题描述】:
我正在尝试使用汇编语言中的 shift 和 add 方法将两个 16 位数字相乘,并将 hi 部分存储在 dx 寄存器中,将低部分存储在 ax 寄存器中。被乘数和乘数在堆栈上传递对于我的一些测试,我可以得到正确的答案,但对于一些,持有较高部分的部分,dx,是错误的。例如,如果我做 0002 次 0001 我得到了我的答案,dx = 0002 ax = 0002,而答案应该是 dx = 0000 ax = 0002。
这是我的代码。我似乎不知道我的代码哪里出错了。我什至手工做了这个例子,但看不到 dx = 0002 部分是如何到达那里的。
;---------------------------------------
; 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
;---------------------------------------
【问题讨论】:
-
您有在计算机上运行的实现吗?还是只是“纸上谈兵”?如果您有一个正在运行的实现,那么使用调试器来单步调试您的程序将大有帮助。
-
mov cx,0Fh使loop计数器 15 不是 16。 -
即使是 16,我也会得到 dx = 0004。是的,我确实在计算机上运行了这段代码,这就是我发现我的测试用例得到不同答案的原因
-
不是每本 MCU 书籍都包含此类事情的示例吗?
-
您正在向右移动乘数并测试它的 ls。少量。您需要将其向左移动并测试其 m.s.位,因为您将产品向左移动。您还需要在添加之前移动产品。
标签: assembly 32-bit multiplication x86-16 16-bit