Tuesday, May 5, 2020

MIPS order of multiplication and division

This is MIPS assembler code that demonstrates the different results one can get depending on the order multiplication and division operations are exeuted. Expected program output:
(N1/N2)*N2 = 8
(N1*N2)/N2 = 10

 The code is fully documented.

Launch EzMIPSthe MIPS assembler simulator, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.

# ----------- ordering of multiplication and division ----------- #

# expeted outptut #
# (N1/N2)*N2 = 8
# (N1*N2)/N2 = 10
# ............... #

# ............................................................... #

.data

szResult1: .asciiz "(N1/N2)*N2 = "
szResult2: .asciiz "\n(N1*N2)/N2 = "

N1:        .word 10
N2:        .word 4

# ............................................................... #

.text

main:

# .................. initialize registers ....................... #

    lw $s0, N1           # $s0 = N1 = 10
    lw $s1, N2           # $s1 = N2 =  4

# .................. calculate (N1/N2)*N2 ....................... #

    div $s0, $s1         # $LO = $s0 / $s1 = 10 / 4 = 2
    mflo $s2             # $s2 = $LO = 2
    mul $s2, $s2, $s1    # $s2 = $s2 * $s1 = 2 * 4 = 8

# ................ print string "(N1/N2)*N2 = " ................. #

    li $v0, 4
    la $a0, szResult1
    syscall

# ............. print integer result of (N1/N2)*N2 .............. #

    li $v0, 1
    move $a0, $s2
    syscall

# .................. calculate (N1*N2)/N2 ....................... #

    mul $s2, $s0, $s1     # $s2 = $s0 * $s1 = 10 * 4 = 40
    div $s2, $s1          # $LO = $s2 / $s1 = 40  /4 = 10
    mflo $s2              # $s2 = $LO = 10

# ................. print string "\n(N1*N2)/N2 = " .............. #

    li $v0, 4
    la $a0, szResult2
    syscall

# ............. print integer result of (N1*N2)/N2 .............. #
    
    addi $v0, $zero, 1
    move $a0, $s2
    syscall

# ................... exit program gracefully ................... #

    li $v0, 10
    syscall

# --------------------------------------------------------------- #

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment