MIPS Assembly & C β MIPS
The instruction and register reference, plus the C-translation questions (if/else with bne, and array code). This is the material behind Q3(b).
Core instructions
| Category | Instruction | Example | Meaning |
|---|---|---|---|
| Arithmetic | add | add $s1,$s2,$s3 | $s1 = $s2 + $s3 |
| subtract | sub $s1,$s2,$s3 | $s1 = $s2 β $s3 | |
| add immediate | addi $s1,$s2,20 | $s1 = $s2 + 20 | |
| Data transfer | load word | lw $s1,100($s2) | $s1 = Memory[$s2+100] |
| store word | sw $s1,100($s2) | Memory[$s2+100] = $s1 | |
| load upper imm. | lui $s1,100 | $s1 = | |
| Logical | and / or / nor | and $s1,$s2,$s3 | bit-wise AND/OR/NOR |
| and/or immediate | andi $s1,$s2,20 | $s1 = $s2 & 20 | |
| shift left/right | sll $s1,$s2,10 | $s1 = $s2 Β« 10 | |
| Branch | branch on equal | beq $s1,$s2,L | if ($s1==$s2) go to L |
| branch not equal | bne $s1,$s2,L | if ($s1!=$s2) go to L | |
| set on less than | slt $s1,$s2,$s3 | $s1 = ($s2<$s3) ? 1 : 0 | |
| Jump | jump | j 2500 | go to target |
| jump & link / reg | jal 2500 Β· jr $ra | call / return |
Register conventions
| Name | Number | Usage |
|---|---|---|
| $zero | 0 | constant 0 |
| $v0β$v1 | 2β3 | results / expression evaluation |
| $a0β$a3 | 4β7 | arguments |
| $t0β$t7 | 8β15 | temporaries |
| $s0β$s7 | 16β23 | saved |
| $t8β$t9 | 24β25 | more temporaries |
| $gp / $sp / $fp / $ra | 28 / 29 / 30 / 31 | global, stack, frame ptr, return addr |
Quick math youβll reuse: $s0=16, $s1=17, $s2=18, $s3=19, $s4=20β¦ and $t0=8, $t1=9β¦ Register number β 5-bit binary by writing the number in binary (e.g. $s2 = 18 = 10010).
Load / arithmetic rule
Arithmetic works on registers only. To use a value from memory you must
lw it into a register first, compute, then sw back.Translating an if/else (Autumn-24 Q3a)
With fβj = $s0β$s4 (so h=$s2, i=$s3, j=$s4):
if (i != j)
h = i + j;
else
h = i - j; Using the decision instruction bne: bne $s3, $s4, Else # if i != j, skip the "then"
add $s2, $s3, $s4 # h = i + j
j Exit
Else: sub $s2, $s3, $s4 # h = i - j
Exit: ...Machine code (bne op=000101, add/sub R-type op=000000, add funct=100000, sub funct=100010):
bne $s3,$s4,Else : 000101 10011 10100 0000000000000010 add $s2,$s3,$s4 : 000000 10011 10100 10010 00000 100000 j Exit : 000010 <26-bit word address of Exit> sub $s2,$s3,$s4 : 000000 10011 10100 10010 00000 100010
The bne offset is 2 because, counting from the instruction after bne, Else is 2 instructions ahead (add, then j).
Array code (Spring-26 Q3b)
Each
int is a word (4 bytes), so p[k] lives at byte address . temp = p[k+1] uses offset , etc. Steps: compute the byte offset with sll/addi, lw the element, operate, sw it back. Pattern: index β Γ4 β base+offset β lw/sw.