如何获取 MIPS 中常量的地址?

How to get the address of a constant in MIPS?

我正在尝试像这样在 mips 中实现 for 循环:

#  {
#     int sum = 0;
#     for(int x = 0; x < n; x++)
#       if ( v[x] > 2 )
#           sum += v[x];
#     return sum;
#  }

我有正确的循环,但我无法正确设置循环的大小。循环按预期运行,但会额外运行一次。它应该打印 31 但它最终 运行 循环了额外的时间并从某处得到 10 然后得到 41 作为最终结果。

这是我的代码:

            .eqv        SIZE        8  
values:     .half       6, 5, 1, 9, -2, 3, 8, 2
endl:       .asciiz     "\n"
endv:

# -------------------------------------------------#  text/code section
.text
.globl  main 
main:
# ------
    #TODO: call doSum(values, SIZE)
    la  $s0, values #&v[0]
    la  $s7, endv   
    li  $a0, 0      #sum = 0

loop:
    lh  $t1, ($s0)  #v[X]
    li  $t2, 2      #$t2 = 2
    bgt $t1, $t2, sumPlus
    j   increment   #skip over sumPlus if not > 2

sumPlus:
    add $a0, $a0, $t1   #sum += v[x]

increment:
    add $s0, $s0, 2 #x++
    blt $s0, $s7, loop

您在 endv 之前有一个换行符和一个空终止符 (endl: .asciiz "\n"),因此您将它们包含在要从中求和的数组中。我不太了解 MIPS,但是因为 \n 的值为 10 (dec) 而 \0 的值为 0。我假设它们是字节,并且这是 运行 在一台机器上little-endian,因此作为带符号的半字,它们被解释为 10 (dec)。

我认为只需将 endv 标签移动到数组的实际末尾(就在 endl: 之前)即可解决此问题。