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.

How to use this article

  1. Read the statement and the expected output of each level, and write your program in Notepad++ (or in the environment at the end).
  2. 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.
  3. If you get stuck, open the hint. If you are still stuck, the solution is further down, explained line by line.
  4. 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.

The gold is not where you thinkhp takes 0x10010000 and 0x10010001; 0x10010002 and 0x10010003 are padding, and gold starts at 0x10010004. lw 2($s0) asks for a word at 0x10010002, which is not a multiple of 4.+0+1+2+30x1001000055000x10010004be0a0000hp: .half 85 gold: .word 27502($s0) = 0x10010002: paddingthe real gold: 0x10010004
SPIM aligns gold to a multiple of 4; counting bytes by hand gives 2 and fails.

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.

ValueDirectiveBytesLoaded withStored withWhy
hp.half2lh (or lhu)shit changes and goes back to its halfword
hmax.half2lh (or lhu)not storedit is only printed
potion.byte1lbunot storedthe healing is never negative and does not change
gold.word4lwswit changes and is a whole word
price.half2lhunot storedit 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:

  • lh for the HP and lbu for the potion. The HP is a halfword; lh or lhu would 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, with lb it would come out as −56 and the potion would do damage.
  • sh $t0, hp stores the HP back as a halfword. With sw, four bytes would have been written and hmax, which comes right after it, would have been overwritten: 87 in the HP and 0 in the max HP.
  • The .align 2 before gold. After hp, hmax and potion come 5 bytes; without the .align, SPIM would still place the .word at 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).
StepInstructionRegisterValue
1lh $t0, hp$t037
2lbu $t1, potion$t150
3add $t0, $t0, $t1$t087
4lw $t2, gold$t2300
5lhu $t3, price$t375
6sub $t2, $t2, $t3$t2225

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.

QuestionOperationResultWhere it goes
How many hours fit in 7384 s?7384 / 36002lo → $s0
What is left?7384 − 2 × 3600184hi → $t2
How many minutes fit in 184 s?184 / 603lo → $s1
What is left?184 − 3 × 604hi → $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 div gives two things: the hours (7384 / 3600 = 2, in lo) and the seconds left over (7384 − 2 × 3600 = 184, in hi). I take both out with mflo and mfhi before the second div, which would overwrite them.
  • The second div is 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.
StepOperationlohi
1div 7384, 36002 (hours)184
2div 184, 603 (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).

ValueBandBitsWhen storingWhen readingWhy
level31-248sll 24srl 24it is the top band: once moved down, there is nothing above it
HP23-816sll 8srl 8 and andi 0xFFFFonce moved down, the level is still on top and has to be removed
class7-08nothingandi 0xFFit 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
The save codelevel 8 shifted 24 bits is 0x08000000, HP 220 shifted 8 bits is 0x0000dc00 and class 3 is 0x00000003. Joined with or they give 0x0800dc03, 134274051 in decimal.level 8 << 240x0800000000001000000000000000000000000000HP 220 << 80x0000dc0000000000000000001101110000000000class 30x0000000300000000000000000000000000000011or, or → code0x0800dc03 = 13427405100001000000000001101110000000011
Each value lands in its own band without overlapping the others: that is why or can join them.

Why it is done this way:

  • Packing: sll moves each value to its band. 8 << 24 = 0x08000000 and 220 << 8 = 0x0000dc00; the class is already in bits 7-0. As the bands do not overlap, or joins them without mixing them: 0x0800dc03 = 134,274,051.
  • lbu and lhu when reading the values: they are unsigned amounts, and with lb a level above 127 would fill the top bits with ones and spoil the or.
  • Unpacking the level only needs srl 24: being the top field, there is nothing above it. If the level could be negative, it would be sra.
  • The HP needs srl 8 and then andi 0xFFFF, because after the shift the level is still on top (0x000800dc). The class, just andi 0xFF.
  • Check: 8 × 16,777,216 + 220 × 256 + 3 = 134,217,728 + 56,320 + 3 = 134,274,051.
StepInstructionResult (hexadecimal)
1sll $t0, $t0, 2408000000
2sll $t1, $t1, 80000dc00
3or $s0, $t0, $t10800dc00
4or $s0, $s0, $t20800dc03
5srl $s1, $t3, 2400000008
6srl $t4, $t3, 8000800dc
7andi $s2, $t4, 0xFFFF000000dc
8andi $s3, $t3, 0xFF00000003

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.

Question 1Single choice

Memory holds a byte 0xF0. What value is left in $t0 after lb $t0, 0($s0)?

  1. 0xFFFFFFF0 (−16)
  2. 0x000000F0 (240)
  3. 0xF0000000
  4. 0x0000000F
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.

Question 2Short answer

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.

Question 3Single choice

With $s0 = 0x10010000, which of these instructions produces Unaligned address?

  1. lw $t0, 6($s0)
  2. lw $t0, 8($s0)
  3. lh $t0, 6($s0)
  4. 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.

Question 4True or false

About sw, sh and sb:

  1. sb writes only the bottom byte of the register and leaves the neighbouring bytes in memory untouched.
  2. sh $t0, 8($s0) writes the 4 bytes of $t0 starting at address $s0 + 8.
  3. sw $t0, 12($s0) can overwrite data at $s0 + 13, $s0 + 14 and $s0 + 15.
  4. 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.

Question 5Single choice

How do you subtract 7 from $t1 in MIPS?

  1. addi $t1, $t1, -7
  2. subi $t1, $t1, 7
  3. sub $t1, $t1, 7
  4. addi $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.

Question 6Fill in the gaps

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.

Question 7Single choice

After mult $t0, $t1 with $t0 = $t1 = 70000, mfhi $t2 gives 1. What does it mean?

  1. That the product does not fit in 32 bits: it is 1 × 2³² plus whatever is in lo.
  2. That the multiplication failed.
  3. That the product is negative.
  4. 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.

Question 8Single choice

What does addiu $t1, $t0, 1 do if $t0 = 2147483647 (0x7FFFFFFF)?

  1. It leaves −2147483648 in $t1, without warning.
  2. It raises the Arithmetic overflow exception.
  3. It leaves 2147483648 in $t1.
  4. 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.

Question 9Match

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.

Question 10Single choice

$t0 is −40. What is $t1 after sra $t1, $t0, 2?

li   $t0, -40
sra  $t1, $t0, 2
  1. −10
  2. 1073741814
  3. −160
  4. 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.

Question 11Single choice

The word 0x00051A30 holds a field in bits 11-8. Which pair of instructions leaves that field as a number in $t1?

  1. srl $t1, $t0, 8 and then andi $t1, $t1, 0xF
  2. Just andi $t1, $t0, 0xF00
  3. sll $t1, $t0, 8 and then andi $t1, $t1, 0xF
  4. 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.

Question 12Order

Put the steps in order to add 10 to the gold stored in gold: .word 2750:

  1. addi $t1, $t1, 10
  2. sw $t1, 0($t0)
  3. lw $t1, 0($t0)
  4. la $t0, gold
Solution

Correct order:

  1. la $t0, gold
  2. lw $t1, 0($t0)
  3. addi $t1, $t1, 10
  4. 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.

  1. Step with F10 and look at $t0 after the 24-bit sll: 08000000. The 8 has moved up six hexadecimal digits.
  2. After the two or, $s0 is 0800dc03: you can read the three values at a glance (08, 00dc and 03).
  3. In the Data tab, the code word (0x10010004) goes from 00000000 to 0800dc03 right after the sw.
  4. Change the class to 255 and the HP to 65535 and check they still don’t overlap: 08ffffff.
  5. Change srl $s1, $t3, 24 to sra and set the level to 200: the level comes out negative.
IC1 exam coming up?The theory and MIPS packs with new solved exams, their cheat sheets, blank exams and .s solutions, for free.See the pack

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/sw 4 bytes (multiple of 4), lh/lhu/sh 2 bytes (even), lb/lbu/sb 1 byte.
  • lb/lh sign-extend; lbu/lhu fill with zeros.
  • There is no subi: addi with a negative. $zero is always 0.
  • add/addi/sub report overflow; addu/addiu don’t.
  • mult → hi:lo (64 bits). div → quotient in lo, remainder in hi.
  • andi/ori/xori pad the immediate with zeros; addi sign-extends it.
  • sll × 2^i, srl ÷ 2^i unsigned, sra ÷ 2^i signed.

Loading and storing

I want to…CodeResult
Read a wordlw $t0, 0($s0)4 bytes from $s0
Read a signed halfwordlh $t0, 6($s0)0x8000 → −32768
Read an unsigned halfwordlhu $t0, 6($s0)0x8000 → 32768
Read a signed bytelb $t0, 9($s0)0xfe → −2
Read an unsigned bytelbu $t0, 10($s0)0xc8 → 200
Store 4, 2 or 1 bytessw / sh / sb $t0, off($s0)Only those bytes change
Load a constantli $t0, 200000lui + ori if it does not fit in 16 bits
The address of a labella $s0, sheet$s0 = 0x10010000

Arithmetic

I want to…CodeResult
Add / subtractadd $t2, $t0, $t1 / sub …Exception if it overflows
Add a constantaddi $t0, $t0, 5Signed 16-bit immediate
Subtract a constantaddi $t0, $t0, -5There is no subi
Copy a registermove $t1, $t0addu $t1, $zero, $t0
Multiply (everything)mult $t0, $t1 + mfhi / mflo64 bits in hi:lo
Multiply (small numbers)mul $t2, $t0, $t1Bottom 32 bits only
Quotient and remainderdiv $t0, $t1 + mflo / mfhiQuotient in lo, remainder in hi

Logic and shifts

I want to…CodeResult with 0000 1011
Is bit 3 set?andi $t1, $t0, 0x088 = yes (0 = no)
Set bit 2 to 1ori $t1, $t0, 0x040000 1111
Flip bit 0xori $t1, $t0, 0x010000 1010
Clear bit 1 (whole word)li $t2, 0xFFFFFFFD + and $t1, $t0, $t20000 1001; the other bits don’t change
NOTnor $t1, $t0, $zeroFlips all 32 bits
Is it odd?andi $t1, $t0, 11 = odd
Multiply by 2^isll $t1, $t0, i40 << 3 = 320
Divide by 2^isra (signed) / srl (unsigned)-40 sra 2 = −10
Index → word offsetsll $t1, $t0, 25 → 20
Pull out bits a..bsrl $t1, $t0, b + andi $t1, $t1, mask0xFD00050B 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

SymptomLikely cause
A byte of 200 comes out as −56lb where lbu belonged
A negative number comes out huge (241, 65531…)lbu/lhu where lb/lh belonged
Unaligned address in inst/data fetchlw/sw at an address that is not a multiple of 4, or lh/sh at an odd one
Arithmetic overflowadd/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 reasonAnother mult or div before taking out hi and lo
The upper half of the word becomes 0andi with a 16-bit immediate
A bit field comes out as 1280 instead of 5andi without bringing the field down first with srl
A signed field comes out as 253 instead of −3srl where sra belonged
A text that came after a value disappearssw where sb or sh belonged

Before you hand it in, ask yourself

  1. Is each value read and stored with the instruction of its size, with the u only if it is never negative?
  2. Are all the offsets aligned (a multiple of 4 for lw/sw, even for lh/sh)? Have you checked it in the Data tab?
  3. Do you take out hi and lo with mfhi/mflo before the next mult or div, and do you get the remainder from hi?
  4. Do your masks fit in 16 bits, or do you build them with li? Do you use sra when the field is signed?
Keep goingAll MIPS articles

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)