我需要撰寫一個程式,如何選??擇 0 到 9 之間的兩個數字并將它們相乘,但我只能使用 SHL、SHR 或 ROR、ROL 命令
;I find this code here on stackoverflow but a don′t really undusted
; ax = x
mov bl, al ; bx = x
shl bl, 3 ; bx = 8 * x
add al, bl ; ax = 9 * x
shl bl, 2 ; bx = 32 * x
add al, bl ; ax = 41 * x
uj5u.com熱心網友回復:
不使用指令執行乘法mul是很清楚的,但是說你只能使用shl, shr,rol和ror指令并不足以解決這個任務。
作為示例,請參見以下子程式,該子程式在不使用mul指令的情況下進行乘法運算:
; IN (al=first number [0,9], ah=second number [0,9]) OUT (ax=product [0,81])
SmallMul:
mov [$ 6], al ; This overwrites the default operand of AAD
mov al, 0
aad ; -> AX is product
ret
add并使用sub它可以制作這個程式嗎?
是的,使用重復添加
example: 5 * 3 --> 0 5 5 5
<--- 3x --->
; IN (al=first number [0,9], bl=second number [0,9]) OUT (cl=product [0,81])
SmallMul:
sub cl, cl ; Sets CL=0
.a: add cl, al
sub bl, 1
jnz .a ; Jumps BL-1 times
ret
- 如果 BL 中的第二個數字為零,那么這個簡單的代碼將失敗!
- 作為優化,我們可以選擇兩個數字中最小的一個來控制回圈。更少的迭代是一件好事。
; IN (al=first number [0,9], bl=second number [0,9]) OUT (cl=product [0,81])
SmallMul:
sub cl, cl ; Sets CL=0
cmp bl, al
jbe .b
xchg bl, al
jmp .b
.a: add cl, al
.b: sub bl, 1
jns .a ; Jumps BL times
ret
移位和添加演算法的簡單版本:
; IN (al=first number [0,9], bl=second number [0,9]) OUT (cl=product [0,81])
SmallMul:
sub cl, cl ; Sets CL=0
jmp .c
.a: add cl, al
.b: shl al, 1 ; Doubles AL, same as `ADD AL, AL`
.c: shr bl, 1 ; Halves BL
jc .a ; Shifted out a 1 bit, so go ADD
jnz .b ; Jumps for as long as BL has non-zero bits
ret
- BL中的第二個數字為零是沒有問題的。
- 作為優化,我們可以選擇兩個數字中最小的一個來控制回圈。更少的迭代是一件好事。
; IN (al=first number [0,9], bl=second number [0,9]) OUT (cl=product [0,81])
SmallMul:
sub cl, cl ; Sets CL=0
cmp bl, al
jbe .c
xchg bl, al
jmp .c
.a: add cl, al
.b: shl al, 1 ; Doubles AL, same as `ADD AL, AL`
.c: shr bl, 1 ; Halves BL
jc .a ; Shifted out a 1 bit, so go ADD
jnz .b ; Jumps for as long as BL has non-zero bits
ret
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528229.html
