装配倍增

时间:2016-10-28 17:53:51

标签: assembly

假设我想在汇编中将大数乘以另一个(可能是小的)数。大数字(被乘数)保存在DX:AX中,乘数保存在BX中。 MUL指令仅适用于AX。那么如何处理DX

例如,数字为0001:0000H(65536),我想将其乘以2.

number     dw   0000h, 0001h
...
mov    ax, [number]
mov    dx, [number+2]
mov    bx, 2
mul    bx   ; it is ax*2 or 0000*2

因此结果为零!有什么想法吗?

1 个答案:

答案 0 :(得分:4)

我们假装这是286,所以你没有eax

number dd 0x12345678      ; = dw 0x5678, 0x1234
result dw 0, 0, 0         ; 32b * 16b = 48b needed
    ...
    mov    ax,[number]    ; 0x5678
    mov    cx,[number+2]  ; 0x1234 ; cx, dx will be used later
    mov    bx,0x9ABC
    ; now you want unsigned 0x12345678 * 0x9ABC (= 0xB00DA73B020)
    mul    bx             ; dx:ax = 0x5678 * 0x9ABC
    ; ^ check instruction reference guide why "dx:ax"!
    xchg   cx,ax
    mov    di,dx          ; di:cx = intermediate result
    mul    bx             ; dx:ax = 0x1234 * 0x9ABC
    ; put the intermediate multiplication results together
    ; into one 48b number dx:di:cx
    add    di,ax
    adc    dx,0
    ; notice how I added the new result as *65536 to old result
    ; by using different 16bit registers

    ; store the result
    mov    [result],cx
    mov    [result+2],di
    mov    [result+4],dx

这与在纸上乘以数字时的方式相同,只是你不会移动* 10个组件,而是利用16b寄存器大小的特性来移动* 65536(0x10000)组件,使其步数更少。 / p>

  13
* 37
----
  91 (13 * 7)
 39_ (13 * 3, shifted left by *base (=10))
---- (summing the intermediate results, the 39 "shifted")
 481 (13 * 37)