我必须在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