MIPS Addition and Subtraction


All arithmetic and logic operations take place in registers. Recall that we have register format instructions and immediate format instructions. We have both formats for addition and subtraction. All addition and subtraction instructions have three operands; the first holds the sum or difference, and the second and third hold the values being added or subtracted.

Addition

add

The add instruction adds two registers and places the result in another register. The format is

     add    Rd, Rs, Rt      # Rd = Rs + Rt

The value that was in Rd before the add is replaced with the sum Rs + Rt. Rs and Rt are unchanged. For example:

     add    $t3, $t1, $t2    # $t3 = $t1 + $t2

addi

The addi instruction adds a register and an immediate value (a constant) and places the result in a register. The format is

     addi   Rd, Rs, immed    # Rd = Rs + immed

The value that was in Rd before the add is replaced with the sum Rs + immed. Rs is unchanged. For example:

     addi   $t2, $t1, 10     # $t2 = $t1 + 10
     addi   $t1, $t1, 1      # $t1 = $t1 + 1 ($t1++)
     addi   $t2, $t1, -5     # $t2 = $t1 - 5

Subtraction

The sub instruction subtracts two registers and places the result in another register. The format is:

     sub    Rd, Rs, Rt      # Rd = Rs - Rt

The value that was in Rd before the sub is replaced with the difference Rs - Rt. Rs and Rt are unchanged. For example:

     sub    $t3, $t1, $t2    # $t3 = $t1 - $t2

The value that was in $t3 before the sub is replaced with the difference $t1 - $t2. $t1 and $t2 are unchanged. Note that there is no subi instruction; to subtract a constant, use addi with a negative constant.



Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2009