multiply two consecutive times in assembly language program

允我心安 提交于 2021-02-05 12:32:50

问题


I am using 8086 emulator and DOSBOX and MASM.

I know that when we multiply 8-bit with 8-bit, answer will be of 16-bit.

al*(8-bit)=ax

And when we multiply 16-bit with 16-bit,answer will of 32-bit.

ax*(16-bit)=dx & ax

But if the answer is in (dx & ax) and I want to multiply 8-bit or 16-bit number then it will simply perform with ax But I needed to multiply a number with answer in (dx & ax). So how to overcome this problem?

I need solve this situation for the factorial program. Where I am trying to find the 10!


回答1:


I am pretty sure there is a duplicate of this somewhere already. Of course it's just elementary maths anyway:

result_low = low(input_low * factor)
result_high = high(input_low * factor) + low(input_high * factor)

Pay attention to saving ax and dx as necessary.




回答2:


Imagine you have to do it in the decimal system, e.g. 37 * 8. You would calculate and add two terms: 30 * 8 + 7 * 8. The first term can be transformed to 3 * 8 * base (10).

37 * 8
------
 56    (7*8)
24     (3*8)
======
296

You see the place of "base" is empty since this value is always 0.

Now let us change base 10 to base "register":

DX:AX * CX
----------
   DX:AX  (AX*CX)
DX:AX     (DX*CX) 
==========
XX:XX:XX

You need two multiplications and three words for the result. Furthermore you have to store the result (DX:AX) from the first multiplication because you need the registers for the second multiplication.

Here's the code for 10! I omit the leftmost word of the result since it isn't needed for 3628800:

.MODEL SMALL
.STACK 1000h

.DATA
Result DD 1                             ; 01 00 00 00 (little endian!)

.CODE

main PROC
    mov ax, @DATA                       ; Initialize DS
    mov ds, ax

    mov cx, 2                           ; Start value

    L1:

    mov ax, WORD PTR Result + 0         ; Low word
    mul cx
    mov di, dx                          ; Store high result
    mov WORD PTR Result + 0, ax         ; Low result won't be changed anymore

    mov ax, WORD PTR Result + 2         ; High word
    mul cx
    add ax, di                          ; add low result from last mul to low result here
    mov WORD PTR Result + 2, ax         ; Store it

    ; adc dx, 0                         ; this would store the "highest" word of result (13!)
    ; mov WORD PTR Result + 4, dx

    add cx, 1
    cmp cx, 10
    jbe L1                              ; While CX <= 10

    mov ax, 4C00h
    int 21h
main ENDP

END main


来源:https://stackoverflow.com/questions/28681607/multiply-two-consecutive-times-in-assembly-language-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!