mul/mult的替代品,用于装配中的乘法(MIPS)? [英] Alternative to mul/mult for multiplication in assembly (MIPS)?

查看:198
本文介绍了mul/mult的替代品,用于装配中的乘法(MIPS)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个类实现一个简单的单周期MIPS处理器,我们实现的唯一操作是lwswjaddiorandaddsubbeqsltjrandijalbnesll.我必须编写一个测试阶乘函数的MIPS文件.显然,我不能使用尚未实现的指令,但是由于阶乘表示:result = n * factorial(n-1),我需要一种将两个值相乘的方法.可以使用前面提到的说明来做到这一点吗?

I'm implementing a simple single-cycle MIPS processor for a class, and the only operations we implemented are lw, sw, j, addi, or, and, add, sub, beq, slt, jr, andi, jal, bne and sll. I have to write a MIPS file testing a factorial function. Obviously, I can't use instructions that haven't been implemented but since factorial means: result = n * factorial(n-1), I need a way to multiply two values. Is there a way to do that with the instructions mentioned earlier?

我开始工作了!这是我的MIPS代码:

I got it working! Here's my MIPS code:

multiply:
add   $v1, $0, $0   # initialize result to 0
loop:
beq   $a2, $0, done  # if second operand reaches 0, the multiplication is over
add   $v1, $v1, $a1 # result = result + first operand
addi  $a2, $a2, -1   # decrements second operand
j     loop           # loops
done:           
jr    $ra             # returns to caller

推荐答案

乘法是简单的重复加法,其方式与重复加法,递增和幂乘法相同.

Multiplication is simply repeated addition, in the same manner that addition is repeated incrementing and exponentiation is repeated multiplication.

因此,您可以编写一个将两个值相乘的函数,如下所示(显然是伪代码,但使用的原始函数足以满足您的要求):

Hence you could write a function that multiplies two values as follows (pseudo-code, obviously, but using functions primitive enough for your specifications):

def mult (a, b):
    result = 0
    while a > 0:
        result = result + b
        a = a - 1
    return result

这仅适用于无符号值,但由于您要进行阶乘,您可能根本不需要 负数.

That's only good for unsigned values as it stands but, since you're doing factorials, you probably don't need to concern yourself with negative numbers at all.

在任何情况下,调整带符号的值应该相对简单,因此,出于完整性考虑,您可以使用:

In any case, it should be relatively simple to adjust for signed values so, in the interests of completeness, you could use:

def mult (a, b):
    # Handle either being zero.

    if a == 0 or b == 0:
        return 0

    # Handle either or both being negative (may
    # need sign change to result).

    sign = 1

    if a < 0:
        a = -a
        sign = -sign

    if b < 0:
        b = -b
        sign = -sign

    # Both now positive, make sure first is not larger (less loops).

    if b < a:
        temp = a
        a = b
        b = temp

    # Multiply small-a by large-b.

    result = 0
    while a > 0:
        result = result + b
        a = a - 1

    # Adjust sign if needed.

    if sign == -1:
        result = -result

    # Et, voila.

    return result

这篇关于mul/mult的替代品,用于装配中的乘法(MIPS)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆