[英]Multiplication using add and shift: translating from Java to MIPS
我必須在MIPS中編寫一個使用add和shift方法將兩個數相乘的程序。 在嘗試了很多次之后,我得到了一個我認為應該工作的程序,但事實並非如此,然后我用Java編寫它,代碼在Java中工作。 然后我嘗試將它從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
最后在srl上復制錯誤:
srl $t1, $t1, 1
除了@Joop Eggen的更正之外,您還必須考慮延遲分支是否到位。 如果您使用的MIPS具有延遲分支,則應相應地修改您的程序。 最簡單的方法是在跳轉/分支之后添加一條nop
指令(在兩個beq
之后和j
之后)。
除此之外,在代碼的末尾,您將結果($ s2)添加到$ a0而不是將其移動到那里。
所以,總結一下:
nop
srl $t0, $t0
更改為srl $t1, $t1, 1
add $a0, $a0
,$ s2以add $a0, $0, $s2
一個使用add和shift方法將兩個整數相乘的程序:
.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 nop $t1, $zero, END
div $t1, $s3
mfhi $t3 # remainder is now in register $t3
beq nop $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 $t1, $t1, 1
j nop LOOP # to jump back to the start of the loop
END:
add $a0, $0, $s2
li $v0, 1
syscall
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.