So I'm building a calculator program in MIPS and I'm trying to write the multiply and divide functions.
Currently I read in the integers in a loop like so:
li $v0, 5
syscall
and then eventually call my functions multi
and divi
depending on which action the user wants to do.
So assuming I have the integers in $a0
and $a1
, what would be a clean way to multiply $a0
by $a1
and/or divide $a0
by $a1
? I've been looking around online but I can't find a clean and easy way to do this, because I have to send the resulting answer back in $v0
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0