32位整数

时间:2015-09-17 22:17:28

标签: arrays mips

所以我目前陷入了一个问题,我很高兴看到有人能详细说明我的问题。

问题列在下面

让寄存器$ s1成为数组A的基础,

注册$ v0是变量X,

注册$ t0为索引i,

然后为以下语句编写MIPS指令

K = A [i] + A [i + 3];

解决方案如下所示

sll $t1, $t0, 2
add $t2, $s1, $t1
lw $t3, 0($t2)
lw $t4, 12($t2)
add $v0, $t3, $t4

我对此问题的解决方案是

addi $t1, $t0, 3  # for the $t1 <- i+3
lw $t2, 0($t1)    # for the $t2 <- A[i+3]
lw $t3, 0($t0)    # for the $t3 <- A[i]
add $v0, $t2, $t3 # for the K <- A[i+3] + A[i]

所以问题是,

我真的不明白为什么解决方案没有通过3(i + 3)添加索引然后从添加的索引加载。

同样是解决方案的第二行,添加$ t2,$ s1,$ t1,如何添加带索引的基数(即$ t2&lt; -A + i)?数组不表示内存堆栈,索引是堆栈的位置地址吗?

提前致谢。

对这个问题进行详细阐述时,我们将非常感激。

1 个答案:

答案 0 :(得分:2)

请记住,A的每个索引都不是32位。 A的每个索引仅为8位。上面的代码执行以下操作:

sll $t1, $t0, 2   # take $t0 and shift it over 2 bits
                  # (equivalent to multiply by 4)
add $t2, $s1, $t1 # from the 0 index, add on $t1 to get into the register for A[i]
lw $t3, 0($t2)    # load 4 bytes (the entire 32bits) from A[i]
lw $t4, 12($t2)   # load 4 bytes (the entire 32bits) from A[i + 3] 
                  # where 3 is actually 12 because it's 8bits per index
                  # so multiply by 4
add $v0, $t3, $t4

要实现的最重要的事情是&#34;数组的8位(字节)与32位(字)索引。&#34;

查看您的代码:

addi $t1, $t0, 3  # actually just moves this over 3 bytes, not 3 words
lw $t2, 0($t1)    # gets the word at A[i / 4]
lw $t3, 0($t0)    # gets the word at A[(i + 3) / 4]
add $v0, $t2, $t3 # and now you can see why this would be wrong.