我必須在MIPS中編寫一個程序,使用add和shift方法將兩個數字相乘。經過許多次嘗試後,我得到了一個我認爲應該可以工作的程序,但是它沒有,然後我用Java編寫了它,而代碼用Java工作。然後我嘗試將它從Java轉換爲MIPS(通常,它更容易讓我從高級語言的代碼翻譯成低級語言),並且在翻譯它之後,它仍然不起作用。這是我寫的代碼,如果有人發現他們有任何問題或知道如何解決問題,請告訴我。使用添加和移位的乘法:從Java翻譯到MIPS
感謝,
在Java:
static int prod = 0;
public static int mult (int mcand, int mier)
{
while (mier != 0)
{
int rem = mier % 2;
if (rem != 0)
{
prod += mcand;
}
mcand = mcand << 1;
mier = mier >> 1;
}
return prod;
}
在MIPS:
# A program that multiplies two integers using the add and shift method
.data # Data declaration section
.text
main: # Start of code section
li $s0, 72 # the multiplicand
li $t0, 72 # the multiplicand in a temporary register
li $s1, 4 # the multiplier
li $t1, 4 # the multiplier in a temporary register
li $s2, 0 # the product
li $s3, 2 # the number 2 in a register for dividing by 2 always for checking if even or odd
LOOP: # first we check if the multiplier is zero or not
beq $t1, $zero, END
div $t1, $s3
mfhi $t3 # remainder is now in register $t3
beq $t3, $zero, CONTINUE # if the current digit is 0, then no need to add just go the shifting part
add $s2, $s2, $t0 # the adding of the multiplicand to the product
CONTINUE: # to do the shifting after either adding or not the multiplicand to the product
sll $t0, $t0, 1
srl $t0, $t0, 1
j LOOP # to jump back to the start of the loop
END:
add $a0, $a0, $s2
li $v0, 1
syscall
# END OF PROGRAM
由於之前沒有人提到過:優化除法。簡而言之,modulo 2相當於「andi register,1」(對不起,我的MIPS技能最近生鏽了) – 2011-12-22 22:12:07