How do I correctly use the mod operator in MIPS?

时光怂恿深爱的人放手 提交于 2020-01-13 10:58:14

问题


In MIPS, I am confused on how to get the mod to work. Below is the code I have come up with thus far. I may have more errors besides the mod, but I feel those errors are a result of the mod misunderstanding. All I'm trying to do is to get the working code (python) here:

i = 1
k = 0
while i < 9:
if i % 2 != 0:
    k = k + i
i += 1
print(k)

to be correctly translated into MIPS. This is my first shot at assembly, so there may be more than mod errors that are tripping me up in the code below:

# Takes the odd integers from 1 to 9, adds them,
#  and spits out the result.
# main/driver starts here
    .globl main

main:

#data segment
.data

Li:     .byte 0x01  # i = 1
Lj:     .byte 0x09  # j = 9
Lk:     .byte 0x00  # k = 0
Ltwo:   .byte 0x02  # 2 for mod usage

# text segment
.text

lb $t0, Li      # temp reg for i
lb $t1, Lj      # j
lb $t2, Lk      # k
lb $t3, Ltwo        # 2

L1:  beq $t0, $t1, L2   # while i < 9, compute
     div $t0, $t3       # i mod 2
     mfhi $t6        # temp for the mod
     beq $t6, 0, Lmod   # if mod == 0, jump over to L1
     add $t2, $t2, $t0  # k = k + i
Lmod:    add $t0, $t0, 1        # i++
     j L1           # repeat the while loop


L2: li $v0, 1       # system call code to print integer
lb $a0, Lk      # address of int to print
syscall

li $v0, 10
syscall

回答1:


You are viewing SPIM registers in hex. Hexadecimal 10 is decimal 16.




回答2:


After working out the kinks, the below code works like a charm. To correctly use the mod operator in MIPS, one must utilize HI and LO. I needed i % 2 == 0 for the statement, so mfhi came in handy. Reference below code for working results:

# Takes the odd integers from 1 to 9, adds them,
#  and spits out the result.
# main/driver starts here
    .globl main

main:

#data segment
.data

Li:     .byte 0x01  # i = 1
Lj:     .byte 0x0A  # j = 10
Lk:     .byte 0x00  # k = 0
Ltwo:   .byte 0x02  # 2 for mod usage


# text segment
.text

lb $t0, Li      # temp reg for i
lb $t1, Lj      # j
lb $t2, Lk      # k
lb $t3, Ltwo        # 2

L1:     beq $t0, $t1, L2    # while i < 9, compute
        div $t0, $t3        # i mod 2
        mfhi $t6           # temp for the mod
        beq $t6, 0, Lmod    # if mod == 0, jump over to Lmod and increment
        add $t2, $t2, $t0   # k = k + i
Lmod:   add $t0, $t0, 1     # i++
        j L1               # repeat the while loop


L2:     li $v0, 1       # system call code to print integer
        move $a0, $t2       # move integer to be printed into $a0
        syscall

        li $v0, 10     # close the program
        syscall


来源:https://stackoverflow.com/questions/21695333/how-do-i-correctly-use-the-mod-operator-in-mips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!