使用add和shift的乘法:从Java转换为MIPS

时间:2011-12-16 10:49:01

标签: java assembly mips multiplication

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

3 个答案:

答案 0 :(得分:3)

最后在srl上复制错误:

srl $t1, $t1, 1

答案 1 :(得分:1)

除了@Joop Eggen的更正之外,您还必须考虑延迟分支是否到位。 如果您使用的MIPS延迟分支,则应相应地修改您的程序。最简单的方法是在跳转/分支之后(在nop之后和beq之后)添加j指令。

除此之外,在代码的末尾,您将结果($ s2)添加到$ a0而不是将其移动到那里。

所以,总结一下:

  • 考虑延迟分支,即在beq和j
  • 之后添加nop
  • srl $t0, $t0,1更改为srl $t1, $t1, 1
  • add $a0, $a0,$ s2更改为add $a0, $0, $s2

答案 2 :(得分:0)

使用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