john turley
john turley

Reputation: 27

mips converting to assembly

I was working with Writing MIPS assembly for the following statement:

f = a - 20 + b + c - d

using the following registers

 $1  a
 $2  b
 $3  c
 $4  d
 $5  f
 $6  g
 $7  i
 $8  j
 $9  A
 10$ D

my answer is this:

 add  $5,$2, $3 // f=b+c
 addi 5$,5$,-20 // f=f+(-20)
 add  $5,$1,5$  // f=a+f 
 sub  $5,$5,$4  // f=f-d
 sw   $5,o($5)  // stores the answer

now the constant -20 is throwing me off a little , and I'm not sure if i handled it right.

or I could do:

 add  $5,$2,$3
 addi $5,$5,20
 sub  $5,$1,$5
 sub  $5,$5, $4
 sw   $5,0($5)

Upvotes: 1

Views: 53

Answers (1)

user35443
user35443

Reputation: 6413

Do not use $1, it's usually reserved for assembler as $at for pseudoinstructions.

Your code could look like this

addui $5, $1, 0xFFEC # or a-20 in twos complement, but it should be the same
addu $5, $5, $2      # 
addu $5, $5, $3      #
subu $5, $5, $4      #

This line

sw $5,o($5) // stores the answer

doesn't make much sense, as you're saving $5 to $5 + o, which looks like a result-dependant location.

Your second code, however, would be incorrect, as it would mean

f = a - (b + c + 20) - d
f = a - b - c - 20 - d

Upvotes: 1

Related Questions