【发布时间】:2019-03-27 05:20:41
【问题描述】:
我有以下代码,但我不断收到算术溢出错误。我要解决的问题是将两个 31 位数字相乘并将结果存储在 $t2 $t3 中并打印出正确的结果。看来我已经编码了两个数字相乘,最终结果是一个 31 位数字。
我很想缩小我觉得自己出错的地方,但老实说,我看不出我需要改变的地方和地方。
# program to multiply two 31 bit binary numbers (A & B),
# using the “shift and add” .
.data
# declare the variable lables of ASCII storage type.
prompt1: .asciiz "Enter number 1: "
prompt2: .asciiz "Enter number 2: "
result: .asciiz "The multiplication of two 31 bit binary numbers is: "
.text
主要:
#prompt1.
li $v0, 4
la $a0, prompt1
syscall
#read number 1 and store in the register $t0
li $v0, 5
syscall
move $t0, $v0
#prompt2.
li $v0, 4
la $a0, prompt2
syscall
#read number 2 and store in the register $t1
li $v0, 5
syscall
move $t1, $v0
li $t2, 0 # The final result of the multiplication
#is saved into the register $t2
li $t3, 1 # Mask for extracting bit!
li $s1, 0 # set the Counter to 0 for loop.
相乘:
#if the Counter $s1 is equal to 31, then go the lable exit
beq $s1, 31, exit
and $s2, $t1, $t3
sll $t3, $t3, 1
beq $s2, 0, increment
add $t2, $t2, $t0
增量:
sll $t0, $t0, 1
addi $s1, $s1, 1
j multiply
退出:
#display the result string.
li $v0, 4
la $a0, result
syscall
#display the result value.
li $v0, 1
add $a0, $t2, $zero
syscall
li $v0, 10 # system call code for exit = 10
syscall # call operating sys
示例输入 A:1143330295(十进制) 样本输入 B:999999223(十进制)
【问题讨论】:
-
您的算法看起来是正确的,但是当您将两个 32 位数字相乘时,结果是 64 位。您可能正在使用 32 位 mips,并且您的算法存在算术溢出。您可以使用 $t3 来存储结果的 lsb 部分,并且在循环中而不是增量移动 $t0,a/ 将 $t2 的 lsb 保留在 $t4 b/
srl $t2 $t2 1和srl $t3,$t3,1c/ 重新注入 lsb $t3 的 msb 中的 $t4 通过将其移动 31 并与 $t3 进行或运算。 -
我的想法是一样的,将它的一部分存储在 $t3 中以避免错误。我尝试实施您所说的,但我认为我正在修改错误的部分。到目前为止,你一直非常有帮助。我相信你会恨我,但你可以根据你的评论修改它。我好像修改错了。抱歉,我是组装新手,仍然有点模糊,也许如果我将您的思维过程可视化,它会让我更清楚。我将不胜感激。我真的很想了解这个过程是如何运作的。
标签: assembly mips mars-simulator