Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly use the mod operator in MIPS?

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
like image 589
kcmallard Avatar asked Feb 11 '14 07:02

kcmallard


People also ask

How do you use modulus operator?

The modulus operator returns the remainder of a division of one number by another. In most programming languages, modulo is indicated with a percent sign. For example, "4 mod 2" or "4%2" returns 0, because 2 divides into 4 perfectly, without a remainder.

What is the mod operator in coding?

The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y.

What is mod in assembly?

The modulo operator divides the value of operand1 by the value of operand2 and returns the remainder after the division. Both operands must be absolute. The result is absolute.

What does the mod operator return?

Remarks. The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (result) equals 5.


1 Answers

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

like image 64
Michael Foukarakis Avatar answered Sep 18 '22 06:09

Michael Foukarakis