div and divu Instructions


To handle both signed integers and unsigned integers, MIPS has two instructions: divide (div) and divide unsigned (divu). The MIPS assembler allows divide instructions to specify three registers, generating mflo or mfhi instructions to place the desired result into a general-purpose register.
div  rd, rs, rt       # signed divide
The instruction divides the contents of rs by the contents of rt, or it can divide rs by the immediate value. It puts the quotient in the destination register rd. Also, the special registers hi contains the remainder, and lo contains the quotient after the divide instruction completes. If the divisor is zero, the machine signals an error and may issue a break instruction.

divu rd, rs, rt       # unsigned divide
Computes the quotient of two unsigned 32-bit values. The instruction description is similar to the one of div.
div mfhi & mflo divu
  .text
  li    $a0, -14
  li    $t0, 4
  div   $a0, $a0, $t0
  li    $v0, 1
  syscall
  .text 
  li    $a0, -14
  div   $a0, $a0, 4
  mfhi  $a0
  li    $v0, 1
  syscall 
  mflo  $a0
  li    $v0, 1
  syscall
  .text
  li    $a0, 14
  divu  $a0, $a0, -4
  mfhi  $a0
  li    $v0, 1
  syscall 
  mflo  $a0
  li    $v0, 1
  syscall
Output Output Output

$a0 =

 


hi (remainder) =

lo (quotient) =

 

hi (remainder) =

lo (quotient) =

 





      Pessimist: Oh, this can’t get any worse!    
      Optimist: Yes, it can!