Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIPS: Integer Multiplication and Division

Tags:

mips

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 dividepending 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

like image 668
Connor Black Avatar asked Apr 17 '13 02:04

Connor Black


People also ask

How do you multiply integers in MIPS?

In MIPS, all integer values must be 32 bits. So if there is a valid answer, it must be contained in the lower 32 bits of the answer. Thus to implement multiplication in MIPS, the two numbers must be multiplied using the mult operator, and the valid result moved from the lo register.

How does division work in MIPS?

The div instruction divides the first argument by the second argument. The quotient is stored in the lowest 32-bits of the result register. The remainder is stored in the highest 32-bits of the result register. Like multiplication, division requires a differentiation between signed and unsigned numbers.

Which of the special registers are used in multiplication and division instructions in MIPS?

The MIPS R4000 can perform multiplication and division in hardware, but it does so in an unusual way, and this is where the temperamental HI and LO registers enter the picture. The HI and LO registers are 32-bit registers which hold or accumulate the results of a multiplication or addition.


1 Answers

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
like image 98
gusbro Avatar answered Dec 01 '22 15:12

gusbro