Load, arithmetic and logic in MIPS — exercises with a potion, the play time and a save code (and the clock that showed 123 minutes)
The day I prepared these exercises, the second one looked like the easiest: turning a game’s seconds into hours, minutes and seconds. I divided the seconds by 3600 for the hours and, for the minutes, divided the seconds by 60 again. With 7384 seconds I got 2 hours and 123 minutes. A game lasting 2 hours and 123 minutes? I had forgotten to take the hours out first: the minutes come from the remainder of the first division, not from the total. 7384 / 60 = 123 minutes is correct… if you haven’t already counted the hours.
This article is for you to do. Three exercises of increasing difficulty with the hero’s sheet, three snippets with a hidden bug, the commented solutions, a practice quiz and a cheat sheet. It all builds on the theory of load, arithmetic and logic in MIPS and on the QtSpim practice.
Table of Contents
How to use this article
- Read the statement and the expected output of each level, and write your program in Notepad++ (or in the environment at the end).
- Run it in QtSpim and compare the console with the expected output. Look at the Data tab too: in these exercises memory is part of the result.
- If you get stuck, open the hint. If you are still stuck, the solution is further down, explained line by line.
- Before the solutions, try the three “What’s wrong here?” snippets: they are the mistakes that come up most often in the lab.
Level 1 · Basic: a potion and a purchase
The hero has 37 HP (out of 120) and 300 gold. They drink a potion that heals 50 and buy the next one, which costs 75. Write a program that updates the HP and the gold in memory and prints them like this. The data segment has to be this one:
.data
hp: .half 37 # current HP
hmax: .half 120 # max HP
potion: .byte 50 # what the potion heals
.align 2
gold: .word 300
price: .half 75 # what the next potion costs
Expected output:
HP: 87 / 120 Gold: 225
Each value is read with the instruction of its size: two .half, one .byte and one .word. None of the four can be negative, so you can use the unsigned versions. And don’t forget to store the new HP and gold with sh and sw.
Level 2 · Intermediate: the play time
The game lasted secs: .word 7384 seconds. Write a program that prints it in hours, minutes and seconds.
Expected output:
Play time: 2 h 3 min 4 s
Two div. The first one, by 3600, gives the hours in lo and what is left in hi. The second one divides that remainder by 60. And take out what you need from the first div before doing the second.
Level 3 · Challenge: the save code
To save the game, the program packs three values into a single word: the level in bits 31-24, the HP in bits 23-8 and the class in bits 7-0. With level 8, HP 220 and class 3 (archer), write a program that builds that word, stores it in code: .word 0, reads it back and pulls the three values out of it.
.data level: .byte 8 class: .byte 3 # 3 = archer hp: .half 220 code: .word 0 # the code is stored here
Expected output:
Code: 134274051 Level: 8 HP: 220 Class: 3
To pack, move each value to its band with sll (24 positions for the level, 8 for the HP) and join them with or. To unpack, the other way round: srl down to position 0 and andi with as many ones as the field has bits (16 for the HP, 8 for the class).
What’s wrong here?
Three short snippets that assemble without errors. Before reading the explanation, predict what each one prints.
Snippet 1
# Snippet 1: the hero's strength
.data
power: .byte 200
.text
.globl main
main: lb $t0, power
li $v0, 1
move $a0, $t0
syscall
li $v0, 10
syscall
What does it print? Think about how a 32-bit register gets filled from a single byte.
It prints this:
-56
200 is 0xc8 = 1100 1000, and its bit 7 is 1. lb does sign extension: it copies that 1 into the top 24 bits and the register becomes 0xffffffc8, which in two’s complement is −56.
Reading with lb a byte that is never negative. Anything above 127 comes out negative, with no warning at all.
The fix is a single letter:
# Snippet 1 fixed: an unsigned byte is read with lbu
.data
power: .byte 200
.text
.globl main
main: lbu $t0, power
li $v0, 1
move $a0, $t0
syscall
li $v0, 10
syscall
200
Always ask yourself “can this byte be negative?”. If the answer is no (a strength, a character, an amount), lbu.
Snippet 2
# Snippet 2: the gold after the HP
.data
hp: .half 85
gold: .word 2750
.text
.globl main
main: la $s0, hp
lw $t0, 2($s0) # the gold comes right after the HP
li $v0, 1
move $a0, $t0
syscall
li $v0, 10
syscall
What does it print? Count the bytes hp takes and look at what type of data gold is.
The console:
Exception 4 [Address error in inst/data fetch] occurred and ignored 0
And the messages panel:
Exception occurred at PC=0x00400028 Unaligned address in inst/data fetch: 0x10010002
hp takes 2 bytes, so it looks as if the gold starts at hp + 2. But gold is a .word and SPIM places it at a multiple of 4: it adds two padding bytes and the gold starts at 0x10010004. The lw asks for a word at 0x10010002, which is not a multiple of 4, and the processor rejects it. The exception is ignored, $t0 is not written and a 0 is printed.
Working out offsets by counting bytes without taking alignment padding into account. The bug only shows up when you run it.
The fix: use the label, which knows where the value ended up (or work out the offset properly, 4):
# Snippet 2 fixed: the label knows where the gold ended up
.data
hp: .half 85
gold: .word 2750
.text
.globl main
main: lw $t0, gold # SPIM added 2 padding bytes: gold is at hp+4
li $v0, 1
move $a0, $t0
syscall
li $v0, 10
syscall
2750
If an lw fails with Unaligned address, look in the Data tab at which address the value really is before touching the code.
Snippet 3
# Snippet 3: what is left of the loot
.data
loot: .word 2750
party: .word 4
.text
.globl main
main: lw $t0, loot
lw $t1, party
div $t0, $t1
mflo $t2 # what is left for the guild
li $v0, 1
move $a0, $t2
syscall
li $v0, 10
syscall
What does it print? 2750 divided by 4 is 687 with 2 left over.
It prints this:
687
The comment says “what is left”, but mflo takes out the quotient: 687, each player’s share. The remainder is in hi.
Mixing up mflo and mfhi after a div. The program works and the number looks reasonable, which is why it is so hard to spot.
# Snippet 3 fixed: the remainder lives in hi
.data
loot: .word 2750
party: .word 4
.text
.globl main
main: lw $t0, loot
lw $t1, party
div $t0, $t1
mfhi $t2 # hi = remainder, lo = quotient
li $v0, 1
move $a0, $t2
syscall
li $v0, 10
syscall
2
The remainder is what is left over, what stays up top: hi. And always check it the other way round: 4 × 687 + 2 = 2750.
Solutions
Level 1 solution
Before the code, the plan: for each value, three questions. How many bytes does it take? Can it be negative? Does it change, so it has to be stored back? The first two choose the load instruction; the third says whether a store is needed, and that store is always the same size as the value.
| Value | Directive | Bytes | Loaded with | Stored with | Why |
|---|---|---|---|---|---|
hp | .half | 2 | lh (or lhu) | sh | it changes and goes back to its halfword |
hmax | .half | 2 | lh (or lhu) | not stored | it is only printed |
potion | .byte | 1 | lbu | not stored | the healing is never negative and does not change |
gold | .word | 4 | lw | sw | it changes and is a whole word |
price | .half | 2 | lhu | not stored | it is only subtracted |
With the table done, the program writes itself. The path that looks shorter, loading everything with lw, breaks as soon as a value is not 4 bytes long, and it hardly ever warns you.
# level1.s: a potion and a purchase (level 1 solution)
.data
hp: .half 37 # current hp
hmax: .half 120 # max hp
potion: .byte 50 # what the potion heals
.align 2 # gold is a word: at a multiple of 4
gold: .word 300
price: .half 75 # what the next potion costs
t_hp: .asciiz "HP: "
t_bar: .asciiz " / "
t_gold: .asciiz "\nGold: "
.text
.globl main
main: lh $t0, hp # 37
lbu $t1, potion # 50 (an unsigned byte: healing is never negative)
add $t0, $t0, $t1 # 87
sh $t0, hp # the HP goes back as a halfword
lw $t2, gold # 300
lhu $t3, price # 75
sub $t2, $t2, $t3 # 225
sw $t2, gold
lh $t4, hmax
li $v0, 4
la $a0, t_hp
syscall
li $v0, 1
move $a0, $t0
syscall
li $v0, 4
la $a0, t_bar
syscall
li $v0, 1
move $a0, $t4
syscall
li $v0, 4
la $a0, t_gold
syscall
li $v0, 1
move $a0, $t2
syscall
li $v0, 10
syscall
HP: 87 / 120 Gold: 225
Why it is done this way:
lhfor the HP andlbufor the potion. The HP is a halfword;lhorlhuwould give the same because 37 is positive. The potion is a byte that is never negative:lbu. If someone stored a potion that heals 200, withlbit would come out as −56 and the potion would do damage.sh $t0, hpstores the HP back as a halfword. Withsw, four bytes would have been written andhmax, which comes right after it, would have been overwritten: 87 in the HP and 0 in the max HP.- The
.align 2beforegold. Afterhp,hmaxandpotioncome 5 bytes; without the.align, SPIM would still place the.wordat the next multiple of 4, but writing it makes it clear in the code that there is padding there. - Check: 37 + 50 = 87 and 300 − 75 = 225. In the Data tab, the first word becomes
00780057(120 and 87) and the one at 0x10010008,000000e1(225).
| Step | Instruction | Register | Value |
|---|---|---|---|
| 1 | lh $t0, hp | $t0 | 37 |
| 2 | lbu $t1, potion | $t1 | 50 |
| 3 | add $t0, $t0, $t1 | $t0 | 87 |
| 4 | lw $t2, gold | $t2 | 300 |
| 5 | lhu $t3, price | $t3 | 75 |
| 6 | sub $t2, $t2, $t3 | $t2 | 225 |
Loading the price with lw instead of lhu. price is at 0x1001000c, which is a multiple of 4, so no exception is raised: lw reads the 75 and the next two bytes, which are the “H” and the “P” of t_hp. That gives 0x5048004b = 1,346,895,947 and the program prints Gold: -1346895647.
Level 2 solution
The plan, in words before instructions: it is what a clock does. Out of 7384 seconds, how many whole hours fit? What does not make up an hour is shared out into minutes, and what does not make up a minute is the seconds. Each “how many fit?” is a quotient, which ends up in lo, and each “what is left” is a remainder, which ends up in hi.
| Question | Operation | Result | Where it goes |
|---|---|---|---|
| How many hours fit in 7384 s? | 7384 / 3600 | 2 | lo → $s0 |
| What is left? | 7384 − 2 × 3600 | 184 | hi → $t2 |
| How many minutes fit in 184 s? | 184 / 60 | 3 | lo → $s1 |
| What is left? | 184 − 3 × 60 | 4 | hi → $s2 |
Why div and not the obvious path of subtracting 3600 while it fits: a single div gives both how many times it fits and what is left, with no loop at all.
What if you divide by 60 first?
That works too, and it is exactly what I half did in the story. 7384 / 60 gives 123 minutes with 4 seconds left over; those 123 minutes still have to be divided by 60: 2 hours with 3 minutes left over. It gives the same, 2 h 3 min 4 s, with the same two div. My bug was not dividing by 60, but printing the 123 minutes without taking the hours out first.
# level2.s: play time in hours, minutes and seconds (level 2 solution)
.data
secs: .word 7384 # seconds played
t_time: .asciiz "Play time: "
t_h: .asciiz " h "
t_m: .asciiz " min "
t_s: .asciiz " s\n"
.text
.globl main
main: lw $t0, secs # 7384
li $t1, 3600
div $t0, $t1 # 7384 / 3600
mflo $s0 # hours = 2
mfhi $t2 # what is left: 184 seconds
li $t3, 60
div $t2, $t3 # 184 / 60 (on what is left, not on 7384)
mflo $s1 # minutes = 3
mfhi $s2 # seconds = 4
li $v0, 4
la $a0, t_time
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, t_h
syscall
li $v0, 1
move $a0, $s1
syscall
li $v0, 4
la $a0, t_m
syscall
li $v0, 1
move $a0, $s2
syscall
li $v0, 4
la $a0, t_s
syscall
li $v0, 10
syscall
Play time: 2 h 3 min 4 s
Why it is done this way:
- The first
divgives two things: the hours (7384 / 3600 = 2, inlo) and the seconds left over (7384 − 2 × 3600 = 184, inhi). I take both out withmfloandmfhibefore the seconddiv, which would overwrite them. - The second
divis on the remainder, 184, not on 7384. That was my 123-minute bug: 184 / 60 = 3 minutes with 4 seconds left over. - Checking it the other way round: 2 × 3600 + 3 × 60 + 4 = 7200 + 180 + 4 = 7384.
| Step | Operation | lo | hi |
|---|---|---|---|
| 1 | div 7384, 3600 | 2 (hours) | 184 |
| 2 | div 184, 60 | 3 (minutes) | 4 (seconds) |
Reusing $t1 in the second div because it already holds a divisor. $t1 is still 3600: 184 / 3600 gives 0 in lo and 184 in hi, and the program prints Play time: 2 h 0 min 184 s.
It is the same pattern you use to get the digits of a number (divide by 10 and keep the remainder) or to know whether a number is a multiple of another (remainder 0). You will come across it in the practical exams.
Level 3 solution
The plan starts on paper: draw the word and mark where each value goes. Each band gives you three things: how many bits it has, how far the value has to be moved up (to the lowest bit of its band) and which mask trims it when reading it back (as many ones as bits).
| Value | Band | Bits | When storing | When reading | Why |
|---|---|---|---|---|---|
| level | 31-24 | 8 | sll 24 | srl 24 | it is the top band: once moved down, there is nothing above it |
| HP | 23-8 | 16 | sll 8 | srl 8 and andi 0xFFFF | once moved down, the level is still on top and has to be removed |
| class | 7-0 | 8 | nothing | andi 0xFF | it is already at the bottom; only what is above has to be cleared |
Why sll and or and not the obvious path of multiplying and adding, as in the check at the end: moving the level up 24 positions is multiplying it by 16,777,216, and sll does it in one instruction, without going through mult. As the bands do not overlap, or joins the bits without mixing them.
# level3.s: the save code of the game (level 3 solution)
# Format: level in bits 31-24, HP in bits 23-8, class in bits 7-0
.data
level: .byte 8
class: .byte 3 # 3 = archer
hp: .half 220
code: .word 0 # the code is stored here
t_code: .asciiz "Code: "
t_lvl: .asciiz "\nLevel: "
t_hp: .asciiz "\nHP: "
t_cls: .asciiz "\nClass: "
.text
.globl main
main: # 1) pack: each field to its place with sll and joined with or
lbu $t0, level
sll $t0, $t0, 24 # level to bits 31-24
lhu $t1, hp
sll $t1, $t1, 8 # HP to bits 23-8
lbu $t2, class # class is already in bits 7-0
or $s0, $t0, $t1
or $s0, $s0, $t2
sw $s0, code
# 2) unpack: bring down with srl and trim with andi
lw $t3, code
srl $s1, $t3, 24 # level (at the very top: no mask needed)
srl $t4, $t3, 8
andi $s2, $t4, 0xFFFF # HP: 16 bits
andi $s3, $t3, 0xFF # class: 8 bits
li $v0, 4
la $a0, t_code
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, t_lvl
syscall
li $v0, 1
move $a0, $s1
syscall
li $v0, 4
la $a0, t_hp
syscall
li $v0, 1
move $a0, $s2
syscall
li $v0, 4
la $a0, t_cls
syscall
li $v0, 1
move $a0, $s3
syscall
li $v0, 10
syscall
Code: 134274051 Level: 8 HP: 220 Class: 3
Why it is done this way:
- Packing:
sllmoves each value to its band. 8 << 24 =0x08000000and 220 << 8 =0x0000dc00; the class is already in bits 7-0. As the bands do not overlap,orjoins them without mixing them:0x0800dc03= 134,274,051. lbuandlhuwhen reading the values: they are unsigned amounts, and withlba level above 127 would fill the top bits with ones and spoil theor.- Unpacking the level only needs
srl 24: being the top field, there is nothing above it. If the level could be negative, it would besra. - The HP needs
srl 8and thenandi 0xFFFF, because after the shift the level is still on top (0x000800dc). The class, justandi 0xFF. - Check: 8 × 16,777,216 + 220 × 256 + 3 = 134,217,728 + 56,320 + 3 = 134,274,051.
| Step | Instruction | Result (hexadecimal) |
|---|---|---|
| 1 | sll $t0, $t0, 24 | 08000000 |
| 2 | sll $t1, $t1, 8 | 0000dc00 |
| 3 | or $s0, $t0, $t1 | 0800dc00 |
| 4 | or $s0, $s0, $t2 | 0800dc03 |
| 5 | srl $s1, $t3, 24 | 00000008 |
| 6 | srl $t4, $t3, 8 | 000800dc |
| 7 | andi $s2, $t4, 0xFFFF | 000000dc |
| 8 | andi $s3, $t3, 0xFF | 00000003 |
Doing only one of the two steps for the HP. Without the srl, andi $s2, $t3, 0xFFFF keeps 0xdc03, the HP and the class mixed together: HP: 56323. Without the andi, 0x000800dc is left, with the level on top: HP: 524508.
Using the class mask, 0xFF, for the HP. With 220 you do not notice, because 220 fits in 8 bits and the output matches the expected one. With an HP of 300 (0x12c) you get HP: 44: bit 8 is lost. The mask is counted by the width of the band, not by the value you test with.
Practice quiz
Twelve questions to check you’ve got it. It is not an exam: it doesn’t count for anything and you can repeat it as many times as you like. Every answer comes with its explanation, including the ones you get right.
Memory holds a byte 0xF0. What value is left in $t0 after lb $t0, 0($s0)?
0xFFFFFFF0(−16)0x000000F0(240)0xF00000000x0000000F
Solution
Answer: 0xFFFFFFF0 (−16)
0xF0 is 1111 0000. Its bit 7 is 1, so lb extends the sign and the register becomes 0xFFFFFFF0, which in two’s complement is −16.
The same byte 0xF0, read with lbu $t0, 0($s0). What decimal value is left in $t0?
Solution
Answer: 240
lbu fills the top 24 bits with zeros: 0x000000F0 = 15 × 16 = 240.
With $s0 = 0x10010000, which of these instructions produces Unaligned address?
lw $t0, 6($s0)lw $t0, 8($s0)lh $t0, 6($s0)lb $t0, 7($s0)
Solution
Answer: lw $t0, 6($s0)
lw and sw need addresses that are a multiple of 4; lh, lhu and sh, even addresses; lb, lbu and sb, any. 0x10010000 + 6 is not a multiple of 4.
About sw, sh and sb:
- sb writes only the bottom byte of the register and leaves the neighbouring bytes in memory untouched.
- sh $t0, 8($s0) writes the 4 bytes of $t0 starting at address $s0 + 8.
- sw $t0, 12($s0) can overwrite data at $s0 + 13, $s0 + 14 and $s0 + 15.
- To store a signed byte you need an instruction other than sb.
Solution
- T — sb writes only the bottom byte of the register and leaves the neighbouring bytes in memory untouched.
- F — sh $t0, 8($s0) writes the 4 bytes of $t0 starting at address $s0 + 8.
- T — sw $t0, 12($s0) can overwrite data at $s0 + 13, $s0 + 14 and $s0 + 15.
- F — To store a signed byte you need an instruction other than sb.
sb writes 1 byte, sh 2 and sw 4, always the bottom ones of the register. Stores have no signed or unsigned version: the bits are copied as they are.
How do you subtract 7 from $t1 in MIPS?
addi $t1, $t1, -7subi $t1, $t1, 7sub $t1, $t1, 7addi $t1, -7, $t1
Solution
Answer: addi $t1, $t1, -7
Subtractions with a constant are done with addi and the negative constant, which the signed 16-bit immediate allows.
Fill in what div $t0, $t1 leaves with $t0 = 47 and $t1 = 5:
The quotient, ____, ends up in register ____ and is taken out with mflo; the remainder, ____, ends up in ____ and is taken out with ____.
Words:
- hi
- 9
- mfhi
- lo
- 10
- 2
- mflo
- 3
Solution
The quotient, 9, ends up in register lo and is taken out with mflo; the remainder, 2, ends up in hi and is taken out with mfhi.
47 = 5 × 9 + 2. div leaves the quotient in lo and the remainder in hi.
After mult $t0, $t1 with $t0 = $t1 = 70000, mfhi $t2 gives 1. What does it mean?
- That the product does not fit in 32 bits: it is 1 × 2³² plus whatever is in lo.
- That the multiplication failed.
- That the product is negative.
- That the remainder of the operation is 1.
Solution
Answer: That the product does not fit in 32 bits: it is 1 × 2³² plus whatever is in lo.
mult leaves a 64-bit product: hi is the top 32 bits. If hi is not 0 (with positive numbers), the result does not fit in a register.
What does addiu $t1, $t0, 1 do if $t0 = 2147483647 (0x7FFFFFFF)?
- It leaves −2147483648 in $t1, without warning.
- It raises the Arithmetic overflow exception.
- It leaves 2147483648 in $t1.
- It leaves 0 in $t1.
Solution
Answer: It leaves −2147483648 in $t1, without warning.
0x7FFFFFFF + 1 = 0x80000000, which signed is −2147483648. addu and addiu do not check for overflow; add, addi and sub do.
Match each goal with the operation that achieves it on a register:
| Know whether bit 3 is 1 | |
| Set bit 3 to 1 | |
| Flip bit 3 | |
| Flip all the bits |
Definitions:
- nor with $zero
- andi with 0x08
- xori with 0x08
- sll by 3
- ori with 0x08
Solution
- Know whether bit 3 is 1 → andi with 0x08
- Set bit 3 to 1 → ori with 0x08
- Flip bit 3 → xori with 0x08
- Flip all the bits → nor with $zero
and keeps only the bits the mask has at 1, or sets them, xor flips them and nor with 0 is the MIPS NOT.
$t0 is −40. What is $t1 after sra $t1, $t0, 2?
li $t0, -40 sra $t1, $t0, 2
- −10
- 1073741814
- −160
- 10
Solution
Answer: −10
sra shifts right filling with the sign bit: −40 / 2² = −10. With srl the sign bit becomes 0 and you get a huge positive.
The word 0x00051A30 holds a field in bits 11-8. Which pair of instructions leaves that field as a number in $t1?
srl $t1, $t0, 8and thenandi $t1, $t1, 0xF- Just
andi $t1, $t0, 0xF00 sll $t1, $t0, 8and thenandi $t1, $t1, 0xF- Just
srl $t1, $t0, 8
Solution
Answer: srl $t1, $t0, 8 and then andi $t1, $t1, 0xF
To pull out a bit field: srl down to position 0 and andi with as many ones as the field has bits.
Put the steps in order to add 10 to the gold stored in gold: .word 2750:
- addi $t1, $t1, 10
- sw $t1, 0($t0)
- lw $t1, 0($t0)
- la $t0, gold
Solution
Correct order:
- la $t0, gold
- lw $t1, 0($t0)
- addi $t1, $t1, 10
- sw $t1, 0($t0)
MIPS is load/store: first the address, then load the value, operate in the register and store it at the same address.
Try it in QtSpim (or right here)
To finish, the save code from level 3, which is the one you learn most from by watching the registers in hexadecimal:
Loading the MIPS environment… If it does not appear, copy level3.s into your QtSpim.
- Step with F10 and look at
$t0after the 24-bitsll:08000000. The 8 has moved up six hexadecimal digits. - After the two
or,$s0is0800dc03: you can read the three values at a glance (08, 00dc and 03). - In the Data tab, the
codeword (0x10010004) goes from00000000to0800dc03right after thesw. - Change the class to 255 and the HP to 65535 and check they still don’t overlap:
08ffffff. - Change
srl $s1, $t3, 24tosraand set the level to 200: the level comes out negative.
Cheat sheet: Load, arithmetic and logic in MIPS
The essentials in 30 seconds
- You only operate in registers: load → operate → store. Address =
$base+ offset. lw/sw4 bytes (multiple of 4),lh/lhu/sh2 bytes (even),lb/lbu/sb1 byte.lb/lhsign-extend;lbu/lhufill with zeros.- There is no
subi:addiwith a negative.$zerois always 0. add/addi/subreport overflow;addu/addiudon’t.mult→hi:lo(64 bits).div→ quotient inlo, remainder inhi.andi/ori/xoripad the immediate with zeros;addisign-extends it.sll× 2^i,srl÷ 2^i unsigned,sra÷ 2^i signed.
Loading and storing
| I want to… | Code | Result |
|---|---|---|
| Read a word | lw $t0, 0($s0) | 4 bytes from $s0 |
| Read a signed halfword | lh $t0, 6($s0) | 0x8000 → −32768 |
| Read an unsigned halfword | lhu $t0, 6($s0) | 0x8000 → 32768 |
| Read a signed byte | lb $t0, 9($s0) | 0xfe → −2 |
| Read an unsigned byte | lbu $t0, 10($s0) | 0xc8 → 200 |
| Store 4, 2 or 1 bytes | sw / sh / sb $t0, off($s0) | Only those bytes change |
| Load a constant | li $t0, 200000 | lui + ori if it does not fit in 16 bits |
| The address of a label | la $s0, sheet | $s0 = 0x10010000 |
Arithmetic
| I want to… | Code | Result |
|---|---|---|
| Add / subtract | add $t2, $t0, $t1 / sub … | Exception if it overflows |
| Add a constant | addi $t0, $t0, 5 | Signed 16-bit immediate |
| Subtract a constant | addi $t0, $t0, -5 | There is no subi |
| Copy a register | move $t1, $t0 | addu $t1, $zero, $t0 |
| Multiply (everything) | mult $t0, $t1 + mfhi / mflo | 64 bits in hi:lo |
| Multiply (small numbers) | mul $t2, $t0, $t1 | Bottom 32 bits only |
| Quotient and remainder | div $t0, $t1 + mflo / mfhi | Quotient in lo, remainder in hi |
Logic and shifts
| I want to… | Code | Result with 0000 1011 |
|---|---|---|
| Is bit 3 set? | andi $t1, $t0, 0x08 | 8 = yes (0 = no) |
| Set bit 2 to 1 | ori $t1, $t0, 0x04 | 0000 1111 |
| Flip bit 0 | xori $t1, $t0, 0x01 | 0000 1010 |
| Clear bit 1 (whole word) | li $t2, 0xFFFFFFFD + and $t1, $t0, $t2 | 0000 1001; the other bits don’t change |
| NOT | nor $t1, $t0, $zero | Flips all 32 bits |
| Is it odd? | andi $t1, $t0, 1 | 1 = odd |
| Multiply by 2^i | sll $t1, $t0, i | 40 << 3 = 320 |
| Divide by 2^i | sra (signed) / srl (unsigned) | -40 sra 2 = −10 |
| Index → word offset | sll $t1, $t0, 2 | 5 → 20 |
| Pull out bits a..b | srl $t1, $t0, b + andi $t1, $t1, mask | 0xFD00050B bits 11-8 → 5 |
Exercise templates
# Update a field of the sheet (level 1)
lh $t0, hp # read with its size
add $t0, $t0, $t1 # operate in registers
sh $t0, hp # store with the same size
# Chained quotient and remainder (level 2)
div $t0, $t1 # first division
mflo $s0 # take both out BEFORE the next one
mfhi $t2
div $t2, $t3 # the second one, on the remainder
# Packing and unpacking fields (level 3)
sll $t0, $t0, 24 # each field to its band
or $s0, $t0, $t1 # join them
srl $t4, $s0, 8 # bring the field down
andi $s2, $t4, 0xFFFF # trim it
Most common mistakes
| Symptom | Likely cause |
|---|---|
| A byte of 200 comes out as −56 | lb where lbu belonged |
| A negative number comes out huge (241, 65531…) | lbu/lhu where lb/lh belonged |
| Unaligned address in inst/data fetch | lw/sw at an address that is not a multiple of 4, or lh/sh at an odd one |
| Arithmetic overflow | add/addi/sub with a result that does not fit in 32 signed bits |
| The remainder comes out as the quotient (or the other way round) | mflo and mfhi swapped |
A mult result changes for no reason | Another mult or div before taking out hi and lo |
| The upper half of the word becomes 0 | andi with a 16-bit immediate |
| A bit field comes out as 1280 instead of 5 | andi without bringing the field down first with srl |
| A signed field comes out as 253 instead of −3 | srl where sra belonged |
| A text that came after a value disappears | sw where sb or sh belonged |
Before you hand it in, ask yourself
- Is each value read and stored with the instruction of its size, with the u only if it is never negative?
- Are all the offsets aligned (a multiple of 4 for
lw/sw, even forlh/sh)? Have you checked it in the Data tab? - Do you take out
hiandlowithmfhi/mflobefore the nextmultordiv, and do you get the remainder fromhi? - Do your masks fit in 16 bits, or do you build them with
li? Do you usesrawhen the field is signed?
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?IC1 practical mock exam — MIPS in QtSpim with other data, subroutines and keyboard input (and why part 1 decides almost everything)


