MIPS: Integer Multiplication and Division

2019-02-03 12:53发布

问题:

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

回答1:

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 HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in LO special register (accessible by 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 HI special register will hold the reminder and LO special register will hold the quotient of the division.

E.g.:

  div $a0, $a1
  mfhi $a2 # reminder to $a2
  mflo $v0 # quotient to $v0


标签: mips