Arrays and strings in MIPS — exercises with extra lives, an encrypted save code and a high score that sneaks into the table (and the code that had a curly brace)
For my game’s story mode I wanted a save code: instead of saving the game as it is (“zoe won 3 to 1”), each letter is swapped for the one three places further on in the alphabet, like the Caesar cipher. The program was the usual string loop: read, check it is lowercase, add 3, write into another string and close it. I ran it:
# nowrap.s: the save code without wrapping round the alphabet
.data
game: .asciiz "zoe won 3 to 1"
code: .space 32
tcode: .asciiz "Code: "
.text
.globl main
main: la $t0, game
la $t1, code
loop: lbu $t2, 0($t0)
beqz $t2, end
blt $t2, 'a', write
bgt $t2, 'z', write
addi $t2, $t2, 3 # 3 letters further on (what if I go past z?)
write: sb $t2, 0($t1)
addi $t0, $t0, 1
addi $t1, $t1, 1
j loop
end: sb $zero, 0($t1)
li $v0, 4
la $a0, tcode
syscall
li $v0, 4
la $a0, code
syscall
li $v0, 10
syscall
Code: }rh zrq 3 wr 1
A curly brace, }, in the middle of my code? z is the last letter: 122 + 3 = 125, and 125 in ASCII is }. My cipher did not know that, after z, the alphabet starts again. The rest was fine (o becomes r, e becomes h…), but one z, y or x was enough to fill the code with symbols. In level 2 you fix it.
These are the arrays and strings in MIPS exercises, after the practice in QtSpim. We are still at the arcade machine: extra lives in a byte array, the encrypted save code and a new high score that has to sneak into a sorted table without breaking it.
Table of Contents
How to use this article
- Read the statement and the expected output of each level, and write the program in Notepad++ (or in the web environment, further down) without looking at the solution.
- If you get stuck, open the hint. It is meant to unblock you, not to give you the code.
- Run it in QtSpim and compare your output with the expected one, character by character. Look at the Data tab too: in this topic many mistakes give no message at all.
- Then compare with the solution: what matters is not that it is identical, but understanding why it is written that way.
Level 1 · Basic: extra lives
The lives of the arcade’s six players are in a byte array: lives: .byte 3, 0, 1, 5, 0, 2. Those with 0 or 1 lives get a bonus of 2 extra lives. Write a program that:
- Copies the array into another byte array,
bonus(reserved with.space 6), adding 2 to those with 0 or 1 lives and copying the rest as it is. - Counts how many players get the bonus.
- Prints the new array, with the numbers separated by spaces, and the counter.
Expected output:
With bonus: 3 2 3 5 2 2 Players with a bonus: 3
It is the loop-with-an-if template, but with two pointers (one in lives and another in bonus) that move +1, because they are bytes. The condition “lives <= 1”, with its opposite: bgt $t3, 1, save. To print the new array, another loop over bonus with lb and syscall 1.
Level 2 · Intermediate: the save code
Write the cipher from the hook, but properly: each lowercase letter is swapped for the one 3 places further on, wrapping round the alphabet (x → a, y → b, z → c). Anything that is not lowercase (spaces, digits) is copied as it is. The code goes into another string, code (.space 32), which has to be closed. Also count the letters encrypted. Use the game "zoe won 3 to 1".
Expected output:
Code: crh zrq 3 wr 1 Letters encrypted: 8
After adding 3, check whether you went past 'z'. If so, subtract 26 (the letters of the English alphabet, which is the one in the ASCII table) and you are back at the start: 122 + 3 − 26 = 99, the 'c'. Watch the order: first “is it lowercase?”, then add, then “did I go past it?”.
Level 3 · Challenge: a high score sneaks into the table
The high-score table is sorted from highest to lowest: scores: .half 15600, 12400, 11050, 9850, 8800, 7320 and their names, "LEO", "MAX", "ZOE", "SAM", "KAI", "ANA". A new high score arrives: EVA with 11500. Write a program that:
- Finds the position where it goes: that of the first score lower than the new one.
- Shifts the scores (and their names) one position down from that position; the last one drops out, because the table still has 6.
- Writes the new score and its name into the gap, prints the place it got and the whole table.
Expected output:
It gets in at place 3 1. LEO 15600 2. MAX 12400 3. EVA 11500 4. ZOE 11050 5. SAM 9850 6. KAI 8800
Use indices, because you need the position for everything. The shift is done from the end backwards (j = 5, 4, 3): scores[j] = scores[j-1]. For the names there is a trick: if you align them with .align 2, each 3-letter name + '\0' is exactly one word, and you move it whole with one lw and one sw.
What’s wrong here?
Three snippets with one bug each. Before reading the explanation, predict what each one prints.
Snippet 1
Counting the characters of the arcade’s message:
# Snippet 1: how many characters the message has
.data
msg: .asciiz "INSERT COIN"
txt: .asciiz "Characters: "
.text
.globl main
main: la $t0, msg
li $s0, 0
loop: lbu $t1, 0($t0)
beqz $t1, end
addi $s0, $s0, 1
addi $t0, $t0, 4 # next character
j loop
end: li $v0, 4
la $a0, txt
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 10
syscall
How many characters will it say INSERT COIN has?
This is what it prints:
Characters: 6
Six? INSERT COIN has 11. The bug is in addi $t0, $t0, 4: it moves word by word, but a character is one byte. The loop only looks at characters 0, 4 and 8 (I, R and O) and on the next lap, at position 12, it is already outside msg, because its '\0' was at 11 and it skipped it. It carries on reading the string behind it, "Characters: ", four by four (C, a and r) until it happens to find a 0, the '\0' of that string:
[10010000] 45534e49 43205452 004e494f 72616843 I N S E R T C O I N . C h a r [10010010] 65746361 203a7372 00000000 00000000 a c t e r s : . . . . . . . .
Count them: I (0), R (4), O (8), C (12), a (16), r (20) and at 24 there is a 00. 6 laps.
Copying the addi ..., 4 from the topic 3 template into a string loop. The worst part is that it gives no error: depending on what is behind it in memory, the number comes out different, and it may match the right one by chance in the statement’s example.
The fix is to move 1 by 1:
# Snippet 1 fixed: in a string you move 1 by 1
.data
msg: .asciiz "INSERT COIN"
txt: .asciiz "Characters: "
.text
.globl main
main: la $t0, msg
li $s0, 0
loop: lbu $t1, 0($t0)
beqz $t1, end
addi $s0, $s0, 1
addi $t0, $t0, 1 # next character: 1 byte
j loop
end: li $v0, 4
la $a0, txt
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 10
syscall
Characters: 11
The pointer step is the size of the data you read: lbu → +1, lh → +2, lw → +4. If the load instruction and the addi do not “say” the same size, something is wrong.
Snippet 2
Writing the winner’s name on the scoreboard, which still shows the one from the previous game:
# Snippet 2: the winner's name on the scoreboard
.data
winner: .asciiz "LEO"
board: .asciiz "MAXIMO__" # what was left from the previous game
txt: .asciiz "Wins: "
.text
.globl main
main: la $t0, winner
la $t1, board
loop: lbu $t2, 0($t0)
beqz $t2, end
sb $t2, 0($t1)
addi $t0, $t0, 1
addi $t1, $t1, 1
j loop
end: li $v0, 4
la $a0, txt
syscall
li $v0, 4
la $a0, board
syscall
li $v0, 10
syscall
What comes out after “Wins:”?
Wins: LEOIMO__
LEOIMO__. The copy wrote L, E and O over M, A and X, but did not close the string: the sb $zero is missing after the loop. So the scoreboard’s '\0' is still where it was, at the end of MAXIMO__, and syscall 4 prints everything up to it. In memory:
[10010000] 004f454c 494f454c 5f5f4f4d 6e695700 L E O . L E O I M O _ _ . W i n [10010010] 00203a73 00000000 00000000 00000000 s : . . . . . . . . . . . . .
Look at the second word, 494f454c: it is L E O I, and the next one goes on with M O _ _.
Trusting that “the new string is already zeroed”. With .space it is true the first time, and that is why the program seems to work. When you reuse a place that already had something in it (the previous game’s scoreboard, a string read from the keyboard twice), the garbage shows up.
The fix, one line after the loop:
j loop
end: sb $zero, 0($t1) # close the copy
li $v0, 4
Wins: LEO
Snippet 3
The arcade’s brand backwards, with brackets so you can see exactly what is printed:
# Snippet 3: the brand backwards
.data
brand: .asciiz "ATARI"
reversed: .space 16
txt: .asciiz "Backwards: ["
txt2: .asciiz "]"
.text
.globl main
main: la $t0, brand
move $t1, $t0
find: lbu $t2, 0($t1)
beqz $t2, copy
addi $t1, $t1, 1
j find
copy: la $t3, reversed
other: blt $t1, $t0, end
lbu $t2, 0($t1)
sb $t2, 0($t3)
addi $t1, $t1, -1
addi $t3, $t3, 1
j other
end: sb $zero, 0($t3)
li $v0, 4
la $a0, txt
syscall
li $v0, 4
la $a0, reversed
syscall
li $v0, 4
la $a0, txt2
syscall
li $v0, 10
syscall
What is between the brackets?
Backwards: []
Nothing. The find loop leaves $t1 on the '\0', and the copy starts straight from there. The first thing written into reversed is that 0, and after it I, R, A, T, A. The letters are in memory, but syscall 4 stops at the first byte, which is a 0:
Forgetting that the pointer that looks for the end stays on the '\0', not on the last letter. When reversing, you always have to step back one before copying.
The fix is step 2 of the reverse template:
copy: addi $t1, $t1, -1 # from the '\0' to the last character
la $t3, reversed
Backwards: [IRATA]
When a string “comes out empty”, look at its first byte in the Data tab. If it is a 0, the problem is in the first thing you wrote, not in the syscall.
Solutions
Level 1 solution
The approach, before the code: for each player there is a single question, “do they have 0 or 1 lives?”, and whatever the answer, something has to be written to bonus. That decides the shape of the loop: the question only jumps over the bonus, and the write stays outside the if, at the end, so that both branches do it.
The path that looks more natural is an if-else with an sb in each branch and a j to skip the other one. It works, but that is two writes to keep identical and one more jump. With the opposite condition, bgt $t3, 1, save, the branch without a bonus has nothing of its own: it just skips two instructions.
# level1.s: 2 extra lives for those with 0 or 1 (level 1 solution)
.data
lives: .byte 3, 0, 1, 5, 0, 2 # each player's lives
n: .word 6
bonus: .space 6 # the new array: one byte per player
tvec: .asciiz "With bonus:"
spc: .asciiz " "
tcount: .asciiz "\nPlayers with a bonus: "
.text
.globl main
main: la $t0, lives # read pointer
la $t1, bonus # write pointer
lw $t5, n
li $t2, 0 # i = 0
li $s0, 0 # how many get a bonus
loop: beq $t2, $t5, end
lb $t3, 0($t0) # lives[i]
bgt $t3, 1, save # opposite of (lives[i] <= 1)
addi $t3, $t3, 2 # extra lives
addi $s0, $s0, 1
save: sb $t3, 0($t1) # bonus[i] = lives[i] (with or without extra)
addi $t0, $t0, 1 # bytes: both pointers +1
addi $t1, $t1, 1
addi $t2, $t2, 1
j loop
end: li $v0, 4
la $a0, tvec
syscall
la $t1, bonus # walk the new array to print it
li $t2, 0
prt: beq $t2, $t5, count
li $v0, 4
la $a0, spc
syscall
lb $a0, 0($t1)
li $v0, 1
syscall
addi $t1, $t1, 1
addi $t2, $t2, 1
j prt
count: li $v0, 4
la $a0, tcount
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 10
syscall
With bonus: 3 2 3 5 2 2 Players with a bonus: 3
Why it is written this way:
- Two pointers, both +1.
livesandbonusare byte arrays, so read withlb, write withsband move both by +1. Ifbonuswere an array of words, the write pointer would move +4 and you would write withsw. lband notlbu: they are numbers of lives, not characters. None is negative here, but if the array had penalties (−1),lbwould read them correctly.bgt $t3, 1, saveis the opposite of “lives <= 1”. If the player has more than 1, the bonus is skipped and it goes straight to storing the value as it is. That way there is only onesb, shared by both branches.- To print, a second loop over
bonus. The array is built first and printed afterwards: that way you check that what is in memory is correct, which is what the statement asks for.
The trace of the first loop:
| i | lives[i] | <= 1? | bonus[i] | Counter |
|---|---|---|---|---|
| 0 | 3 | No | 3 | 0 |
| 1 | 0 | Yes | 0 + 2 = 2 | 1 |
| 2 | 1 | Yes | 1 + 2 = 3 | 2 |
| 3 | 5 | No | 5 | 2 |
| 4 | 0 | Yes | 2 | 3 |
| 5 | 2 | No | 2 | 3 |
Three players with a bonus: the ones that had 0, 1 and 0 lives.
Not repeating la $t1, bonus before the second loop. When the first one ends, $t1 is at bonus + 6, which is where tvec starts, and it prints the ASCII codes of “With b”: With bonus: 87 105 116 104 32 98. The counter still comes out as 3, so you only notice by looking at the array.
Not repeating li $t2, 0. $t2 is already 6, beq $t2, $t5, count jumps straight away and no number is printed: With bonus: and on the next line Players with a bonus: 3.
Level 2 solution
The approach is a funnel of three questions per character, always in the same order. Four characters of the game show every path:
| Character | Lowercase? | After adding 3 | Past z (122)? | What is written | Why |
|---|---|---|---|---|---|
z (122) | Yes | 125 | Yes | 125 − 26 = 99, c | it wraps round |
o (111) | Yes | 114 | No | 114, r | it lands inside the alphabet |
| space (32) | No | nothing added | not asked | 32, space | it goes out through write without counting |
3 (51) | No | nothing added | not asked | 51, 3 | digits are not encrypted |
The first two rows go through count; the last two go straight to write. That is why the counter gives 8 and not 14, which is the length of the string.
# level2.s: the save code, each lowercase letter 3 places further on (level 2 solution)
.data
game: .asciiz "zoe won 3 to 1" # what has to be encrypted
code: .space 32 # the encrypted string
tcode: .asciiz "Code: "
tcount: .asciiz "\nLetters encrypted: "
.text
.globl main
main: la $t0, game
la $t1, code
li $s0, 0 # letters encrypted
loop: lbu $t2, 0($t0)
beqz $t2, end
blt $t2, 'a', write # opposite of (c >= 'a')
bgt $t2, 'z', write # opposite of (c <= 'z')
addi $t2, $t2, 3 # 3 letters further on
ble $t2, 'z', count # if it does not go past z, done
addi $t2, $t2, -26 # it went too far: back to the start of the alphabet
count: addi $s0, $s0, 1
write: sb $t2, 0($t1)
addi $t0, $t0, 1
addi $t1, $t1, 1
j loop
end: sb $zero, 0($t1) # close the code
li $v0, 4
la $a0, tcode
syscall
li $v0, 4
la $a0, code
syscall
li $v0, 4
la $a0, tcount
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 10
syscall
Code: crh zrq 3 wr 1 Letters encrypted: 8
Why it is written this way:
- The order of the questions matters. First “is it lowercase?” (if not, it is written as it is). Then 3 is added. And only then “did I go past z?”. If you asked “will I go past it?” before adding, you would have to ask about x, y and z one by one.
ble $t2, 'z', countis the opposite of “I went past it” (c > 'z'): if it did not, the correction is skipped. If it did,addi $t2, $t2, -26sends it back to the start of the alphabet.- The counter is at
count, which both branches go through (with and without wrapping): that way all eight letters count the same.
Checking by hand the letter that wraps: z (122) + 3 = 125 > 122, so 125 − 26 = 99 = c. The others do not go past: o (111) + 3 = 114 = r; e (101) + 3 = 104 = h; w (119) + 3 = 122 = z, right on the edge, so it does not wrap; n → q and t → w. Letters encrypted: z, o, e, w, o, n, t and o = 8. The 3 and the 1 do not change.
Why subtract 26 and not take the “remainder mod 26” path you see in other languages, (c − 'a' + 3) % 26 + 'a': in MIPS that remainder needs a div and an mfhi, on top of the two subtractions and the addition. Since only 3 is added, a letter can never go past more than once, and one comparison and one subtraction are enough.
Writing blt $t2, 'z', count instead of ble. The z is encrypted correctly, but a letter that lands exactly on z goes too far: the w of “won” (119 + 3 = 122) becomes 122 − 26 = 96, the grave accent, and the code shows that symbol where the z should be. That is why it is worth always testing w, x, y and z.
Level 3 solution
The approach, in words: it is what you do with a paper table. First you look from top to bottom for where EVA gets in. Then you make room by pushing down everything from there, starting at the end so you do not overwrite anything. And finally you write EVA in the gap. Three steps, three pieces of the program, with the same pos.
The obvious path, putting the score at the end and sorting the table, goes through the table several times when it is already sorted except for one element.
# level3.s: insert a new high score into the sorted table (level 3 solution)
.data
scores: .half 15600, 12400, 11050, 9850, 8800, 7320 # from highest to lowest
n: .word 6
new: .half 11500 # the score that arrives
.align 2 # the names start at a multiple of 4
names: .asciiz "LEO", "MAX", "ZOE", "SAM", "KAI", "ANA" # 4 bytes = 1 word each
who: .asciiz "EVA" # the name of the new high score
dot: .asciiz ". "
spc: .asciiz " "
nl: .asciiz "\n"
tplace: .asciiz "It gets in at place "
.text
.globl main
main: la $s2, scores
la $s3, names
lw $s4, n
lh $s5, new # $s5 = 11500
# --- 1. find the position: the first score lower than the new one ---
li $s0, 0 # pos = 0
find: beq $s0, $s4, quit # it beats none: it does not get in
sll $t0, $s0, 1
add $t0, $t0, $s2
lh $t1, 0($t0) # scores[pos]
blt $t1, $s5, shift # scores[pos] < new: it goes here
addi $s0, $s0, 1
j find
# --- 2. shift backwards from the end: j = n-1 ... pos+1 ---
shift: addi $t2, $s4, -1 # j = n - 1 (the last one drops out)
down: ble $t2, $s0, put # opposite of (j > pos)
sll $t0, $t2, 1 # scores[j] = scores[j-1]
add $t0, $t0, $s2
lh $t1, -2($t0) # -2: the halfword before it
sh $t1, 0($t0)
sll $t0, $t2, 2 # names[j] = names[j-1]
add $t0, $t0, $s3
lw $t1, -4($t0) # a whole name at once (4 bytes)
sw $t1, 0($t0)
addi $t2, $t2, -1 # j = j - 1
j down
# --- 3. write the new one at pos ---
put: sll $t0, $s0, 1
add $t0, $t0, $s2
sh $s5, 0($t0) # scores[pos] = new
sll $t0, $s0, 2
add $t0, $t0, $s3
lw $t1, who # "EVA" + '\0' fits in one word
sw $t1, 0($t0) # names[pos] = who
li $v0, 4
la $a0, tplace
syscall
li $v0, 1
addi $a0, $s0, 1 # place = pos + 1
syscall
li $v0, 4
la $a0, nl
syscall
# --- 4. print the table ---
quit: li $t2, 0 # i = 0
table: beq $t2, $s4, bye
li $v0, 1
addi $a0, $t2, 1
syscall
li $v0, 4
la $a0, dot
syscall
sll $t0, $t2, 2
add $a0, $t0, $s3 # names[i]
li $v0, 4
syscall
li $v0, 4
la $a0, spc
syscall
sll $t0, $t2, 1
add $t0, $t0, $s2
lh $a0, 0($t0) # scores[i]
li $v0, 1
syscall
li $v0, 4
la $a0, nl
syscall
addi $t2, $t2, 1
j table
bye: li $v0, 10
syscall
It gets in at place 3 1. LEO 15600 2. MAX 12400 3. EVA 11500 4. ZOE 11050 5. SAM 9850 6. KAI 8800
Why it is written this way:
- Finding the position is a “first occurrence” from the theory: the first
scores[pos]lower than the new one. 15600 and 12400 are not; 11050 < 11500, sopos = 2(place 3). If none were lower,poswould reachnand the program would jump to printing the table without touching it: the score does not get in. - The shift goes from the bottom up.
jstarts atn − 1 = 5and goes down topos + 1 = 3:scores[5] = scores[4], thenscores[4] = scores[3]andscores[3] = scores[2]. If it went from the top down, you would copy ZOE into 3, then 3 (which is already ZOE) into 4… and the whole table would end up being ZOE. lh $t1, -2($t0)andlw $t1, -4($t0)read the previous element without computing another address: the instruction’s negative offset does thej − 1..align 2before the names places them at an address that is a multiple of 4 (here0x10010014). That way each name ("LEO"+'\0') is an aligned word and is moved whole withlw/sw. Without the.align,lwwould give Unaligned address if the names landed on an address that is not a multiple of 4.lw $t1, wholoads the 4 bytes of"EVA\0"at once andswwrites them into the gap: the new name,'\0'included.
The search, loop by loop:
| pos | scores[pos] | Lower than 11500? | What it does |
|---|---|---|---|
| 0 | 15600 | No | pos = 1 and carries on |
| 1 | 12400 | No | pos = 2 and carries on |
| 2 | 11050 | Yes | jumps to shift with pos = 2 |
Removing the .align 2. The names then start right after new, at 0x10010012: it is even, but not a multiple of 4, and that is enough for it to fail. The first lw of the shift (j = 5) reads at 0x10010022 and QtSpim gives Unaligned address in inst/data fetch: 0x10010022.
What if EVA ties with ZOE (11050)?
blt is strict: 11050 is not lower than 11050, so the search carries on and stops at SAM (9850), with pos = 3. It prints It gets in at place 4, with ZOE at 3 and EVA at 4: in a tie, whoever was already there stays ahead. If you wanted the opposite, changing blt to ble would be enough.
With 7000, none is lower, pos reaches 6 and it jumps to quit: the place line is not printed and the table stays the same.
The trace of the shift:
| j | Copy | scores afterwards | names afterwards |
|---|---|---|---|
| 5 | j−1 = 4 → 5 | …, 8800, 8800 | …, KAI, KAI |
| 4 | 3 → 4 | …, 9850, 9850, 8800 | …, SAM, SAM, KAI |
| 3 | 2 → 3 | …, 11050, 11050, 9850, 8800 | …, ZOE, ZOE, SAM, KAI |
| 2 | (j <= pos: stop) | 11500 is written at 2 | EVA is written at 2 |
Practice quiz
Twelve questions on the whole topic: sizes and sign, the index with sll, strings and their '\0', transforming, reversing and searching. It does not count for anything: it is there to show you what you have clear and what you do not, so you can repeat it as many times as you like. Every answer has its explanation.
You walk an array declared with .half using a pointer. How much does the pointer have to add every lap?
- 2
- 1
- 4
- 8
Solution
Answer: 2
The pointer holds an address, and addresses count bytes. .byte moves 1, .half moves 2 and .word moves 4.
Complete the load and step for each kind of array.
.word array: read with ____ and the pointer adds ____. .half array: read with ____ and it adds ____. .byte array: read with ____ and it adds ____.
Words:
- 4
- sw
- la
- lb
- lh
- 8
- 2
- 1
- lw
Solution
.word array: read with lw and the pointer adds 4. .half array: read with lh and it adds 2. .byte array: read with lb and it adds 1.
Each load reads exactly the size of the element (lw 4 bytes, lh 2, lb 1) and the pointer moves that same number of bytes. sw stores (it does not read) and la loads an address, not a value.
A byte in memory holds 0xFD. What is left in $t0 after lbu $t0, 0($t1)?
- 253
- -3
- 0xFD000000
- An error, because the byte is negative
Solution
Answer: 253
0xFD = 1111 1101. With lb the sign is extended and it is −3; with lbu it is filled with zeros and it is 253. In sign.s, the same list of changes added up to 0 with lb and 512 with lbu.
An array lives: .word … starts at 0x10010000. At which address is lives[5]?
- 0x10010014
- 0x10010005
- 0x10010020
- 0x10010010
Solution
Answer: 0x10010014
Address = base + i · size = 0x10010000 + 5 · 4 = 0x10010000 + 20. And 20 in hexadecimal is 0x14.
Put the instructions in order to read A[i] from a word array with the index in $s3 and the base in $s6.
lw $t0, 0($t1)(A[i])add $t1, $t1, $s6(base + i · 4)sll $t1, $s3, 2(i · 4)
Solution
Correct order:
sll $t1, $s3, 2(i · 4)add $t1, $t1, $s6(base + i · 4)lw $t0, 0($t1)(A[i])
First the index is turned into bytes, then the base is added to get the address and, with it, the value is loaded. It is the while (A[i] == k) from the lecture notes.
About .asciiz strings:
.asciiz "LEO"takes 4 bytes..ascii "LEO"also adds the ‘\0’ at the end.- Syscall 4 prints from
$a0until it finds a 0 byte. - To walk a string you do not need its length: stopping at the ‘\0’ is enough.
Solution
- T —
.asciiz "LEO"takes 4 bytes. - F —
.ascii "LEO"also adds the ‘\0’ at the end. - T — Syscall 4 prints from
$a0until it finds a 0 byte. - T — To walk a string you do not need its length: stopping at the ‘\0’ is enough.
.asciiz stores the characters plus a 0 byte (that is why LEO takes 4). .ascii does not add that 0. Syscall 4 knows nothing about lengths: it prints up to the first 0, which is why a string loop stops with lbu + beqz.
A buffer board held "MAXIMO__". You copy "LEO" over it character by character, but after the loop you do not run sb $zero, 0($t1). What does syscall 4 print with board?
end: li $v0, 4
la $a0, board
syscall- LEOIMO__
- LEO
- MAXIMO__
- LEO__
Solution
Answer: LEOIMO__
It is Snippet 2 of the exercises: the console showed Wins: LEOIMO__. Without the sb $zero, the copy ends wherever the old contents of the buffer ended.
To count the characters of "INSERT COIN" someone writes addi $t0, $t0, 4 inside the loop. What happens?
- It only looks at one character in four and can skip the ‘\0’ and keep reading the data behind it
- It counts 11, but takes four times as long
- It gives Unaligned address
- It counts 3, because 11 / 4 = 2.75
Solution
Answer: It only looks at one character in four and can skip the ‘\0’ and keep reading the data behind it
A character takes 1 byte. With +4, the loop reads characters 0, 4, 8, 12… The ‘\0’ is at position 11 and is never read, so it keeps going through memory until it happens to find a 0.
The ASCII code of 'a' is 97. Which code does the letter have after addi $t2, $t2, -32 if $t2 held the 'a'?
Solution
Answer: 65
97 − 32 = 65, which is 'A'. In ASCII every lowercase letter is 32 places after its capital (0x61 versus 0x41: only bit 5 changes).
You want to copy a string backwards into another one. Which steps are needed? (tick all the necessary ones)
- Find the ‘\0’ of the original to know where it ends
- Step back one position from the ‘\0’ before you start copying
- Close the new string with
sb $zero - Use
lwto read four letters at once - Make the read pointer move +1
Solution
Answer: Find the ‘\0’ of the original to know where it ends · Step back one position from the ‘\0’ before you start copying · Close the new string with sb $zero
The reverse.s template: find the end, addi $t1, $t1, -1, copy with reading at −1 and writing at +1 until you pass the start, and close with sb $zero.
Match each instruction with what it does.
lb | |
lbu | |
lh | |
sb |
Definitions:
- Reads a byte and fills with zeros
- Stores a whole word
- Reads a signed halfword
- Stores the low byte of a register
- Reads a byte and extends its sign
Solution
lb→ Reads a byte and extends its signlbu→ Reads a byte and fills with zeroslh→ Reads a signed halfwordsb→ Stores the low byte of a register
Loads with u (lbu, lhu) fill with zeros; without u, they copy the sign bit. Stores (sb, sh, sw) save the low part of the register of the size they name: sb one byte, sh two and sw four.
In search.s (first occurrence of a value in lives: .byte 3, 1, 0, 5, 0, 2) you remove the j end that comes right after move $s0, $t2. Which position does it print now when searching for 0?
- 4
- 2
- -1
- It gets stuck in an infinite loop
Solution
Answer: 4
We checked it by running it: First player with 0 lives: 4. A first-occurrence search has to leave as soon as it finds the value; without that jump it walks the whole array and keeps the last one.
Try it in QtSpim (or right here)
The level 3 solution is the one that makes most sense when you watch it move. Open it in QtSpim or in the environment below:
Loading the MIPS environment… If it does not appear, copy level3.s into your QtSpim.
- Before running, look at the Data tab: the scores are at
0x10010000, the new one (11500 =0x2cec) at0x10010010and the names, thanks to.align 2, at0x10010014. - Put a breakpoint on
shiftand run with F5:$s0is 2, the position where EVA goes. - Carry on with F10 through the
downloop and watch the names change in the right-hand column of the Data tab: KAI is duplicated, then SAM, then ZOE. - Change the new score to 5000 and run it:
posreaches 6 without finding any lower score, the program jumps to printing and the table comes out as it was, with ANA in place 6 and no “It gets in at place” line. - Remove the
.align 2and run it: now the names start right afternew, at0x10010012, and everylw/swon the names gives Unaligned address (SPIM ignores them and carries on). The scores do move, but the names do not, and the table ends up saying that ZOE has 11500. That is why the.alignis there.
Cheat sheet: Arrays and strings in MIPS
The essentials in 30 seconds
- Size rules:
.word4 bytes (lw, +4),.half2 (lh, +2),.byte1 (lb/lbu, +1). - By index: address = base + i · size, with
sll(2 for ×4, 1 for ×2) +add+ load. - A string ends in
'\0': walk it withlbu+beqz, moving +1. - If you build a string:
.space Nwith room to spare, two pointers,sbin the loop andsb $zeroat the end. - Before transforming a character, check its range with the opposite condition.
Arrays and strings
| I want to… | Code | Result |
|---|---|---|
Read A[i] of words | sll $t1, $s3, 2 · add $t1, $t1, $s6 · lw $t0, 0($t1) | $t0 = A[i] |
Read A[i] of halfwords | sll $t1, $s3, 1 · add · lh | $t0 = A[i] |
| Read a character and move on | lbu $t2, 0($t0) · addi $t0, $t0, 1 | Unsigned character |
| Stop at the end of a string | beqz $t2, end | Leaves on the '\0' |
| Write a character | sb $t2, 0($t1) · addi $t1, $t1, 1 | One byte written |
| Close a string | sb $zero, 0($t1) | A '\0' at $t1 |
| Is it lowercase? | blt $t2, 'a', no · bgt $t2, 'z', no | If it carries on, it is |
| Turn into a capital | addi $t2, $t2, -32 | 'a' (97) → 'A' (65) |
| Print a character | move $a0, $t2 · li $v0, 11 · syscall | One letter on the console |
| Read the previous element | lh $t1, -2($t0) / lw $t1, -4($t0) | A[j-1] with no other calculation |
| Align to a word | .align 2 | Whatever comes next at a multiple of 4 |
Templates
Walking a string up to its '\0':
la $t0, string # read pointer
loop: lbu $t2, 0($t0) # current character
beqz $t2, end # '\0': it is over
# ... work with $t2 ...
addi $t0, $t0, 1 # next character
j loop
end:
Building another string (copying, transforming, filtering):
la $t0, source # reading
la $t1, target # writing (.space N)
loop: lbu $t2, 0($t0)
beqz $t2, end
# ... check / transform $t2 ...
sb $t2, 0($t1) # write (when filtering, only if it applies)
addi $t1, $t1, 1
addi $t0, $t0, 1
j loop
end: sb $zero, 0($t1) # ALWAYS close it
Reversing into another string:
la $t0, source
move $t1, $t0
find: lbu $t2, 0($t1) # 1. find the '\0'
beqz $t2, back
addi $t1, $t1, 1
j find
back: addi $t1, $t1, -1 # 2. last letter
la $t3, target
copy: blt $t1, $t0, end # 3. read -1, write +1
lbu $t2, 0($t1)
sb $t2, 0($t3)
addi $t1, $t1, -1
addi $t3, $t3, 1
j copy
end: sb $zero, 0($t3) # 4. close
Exercise templates
| Exercise | Key idea | Result |
|---|---|---|
| Level 1: extra lives | Two pointers +1, bgt $t3, 1 skips the bonus, a single sb | 3 2 3 5 2 2, 3 with a bonus |
| Level 2: save code | lowercase? → +3 → > 'z'? → −26 | crh zrq 3 wr 1, 8 letters |
| Level 3: new high score | Find pos (first lower), shift from j = n−1 to pos+1 with −2/−4, write | EVA gets in at place 3 |
| Theory: high score and its name | One index, sll 1 for scores and sll 2 for names | LEO with 15600 |
| Theory: first occurrence | pos = −1 and j end when found | 2 (and −1 if it is not there) |
Mistakes that come up most
| Symptom | Likely cause | |
|---|---|---|
| The character count does not add up | addi +4 in a string: move +1 | |
| Part of another name comes out | Index without sll on elements bigger than 1 byte | |
| Unaligned address in inst/data fetch | lw/lh at an address that is not a multiple of 4/2: missing sll or .align | |
| The new string ends with old letters | sb $zero is missing after the loop | |
| The reversed string comes out empty | You started copying from the '\0': addi $t1, $t1, -1 is missing | |
| The string is cut at the first space | You subtracted 32 from everything: check it is lowercase | |
{, ` | or }` appear in a cipher | You went past 'z' without wrapping round (−26) |
| The whole table repeats the same element | You shifted from the top down: do it from the end |
Before you hand it in, ask yourself
- Does the step of each pointer match the size it reads or writes (+1, +2, +4)?
- Is each index multiplied by the size of its own array before adding it to the base?
- Does every string I build end with
sb $zero, and does its.spacehave room to spare? - Does it work “for any array or string”, or only with the example (a z at the end, a score that does not get in, a string without spaces)?
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)


