Arrays and strings in MIPS — theory with a high-score table, the index you have to scale and strings that end in ‘\0’ (and the high score that belonged to AM)
Fourth IC1 lab session. I already knew how to walk the wave of enemies with a pointer and a j loop, so I went for something flashier: the high-score table of an arcade machine. Six scores stored as halfwords (.half, none of them goes over 32767) and, separately, the six three-letter names, just like on the machines in an arcade. The program had to find the highest score and say whose it was. I walked the scores with a pointer that moved 2 by 2, kept the position of the maximum in $s1 and, for the name, added that position to the address of names:
# hook.s: the name of the high score (or so I thought)
.data
scores: .half 9850, 15600, 7320, 12400, 11050, 8800 # 6 high scores, one halfword each
n: .word 6 # how many scores there are
names: .asciiz "SAM", "LEO", "ANA", "MAX", "ZOE", "KAI" # 4 bytes per name
txt1: .asciiz "Record: "
txt2: .asciiz " with "
txt3: .asciiz " points\n"
.text
.globl main
main: la $t0, scores # pointer to the first score
lw $t1, n # $t1 = 6, the loop limit
li $t2, 0 # i = 0
li $s0, -1 # maximum = -1 (any score beats it)
li $s1, 0 # position of the maximum
loop: beq $t2, $t1, end # if i == n, I have checked them all
lh $t3, 0($t0) # $t3 = score i (halfword)
ble $t3, $s0, next # if it does not beat the maximum, move on
move $s0, $t3 # new maximum
move $s1, $t2 # and its position
next: addi $t0, $t0, 2 # next score (halfword = 2 bytes)
addi $t2, $t2, 1 # i = i + 1
j loop
end: li $v0, 4
la $a0, txt1
syscall
la $a0, names # address of the first name
add $a0, $a0, $s1 # ... plus the position of the high score
li $v0, 4 # print the name
syscall
li $v0, 4
la $a0, txt2
syscall
li $v0, 1 # print the high score
move $a0, $s0
syscall
li $v0, 4
la $a0, txt3
syscall
li $v0, 10 # end of the program
syscall
And on the console:
Record: AM with 15600 points
AM? There is no AM in my table. The 15600 points belong to LEO, the second one in the list. No error, no warning: SPIM happily printed a name that does not exist. The bug is in a single line, add $a0, $a0, $s1. I was adding the position of the high score (1), but memory does not count names: it counts bytes. Each name takes 4 bytes (three letters and their '\0'), so LEO starts 4 bytes after SAM, not 1. With +1, the address landed in the middle of SAM, on its A, and syscall 4 printed from there up to the first 0: “AM”.
Today is about everything you need to work with lots of data at once and with text: how the walk changes with the size of each element (.word, .half, .byte), what happens to the sign when you read bytes and halfwords, indexed access with sll + add (the famous while (A[i] == k) from the lecture notes), .asciiz strings and their '\0', how to write into a second array or string and close it, how to transform characters (capitals, ranges), how to reverse a string and how to search (the maximum and the first occurrence). We start from the loop template in the branches, conditionals and loops theory, with the word array and the +4 pointer, and we will not repeat it. Then, in the arrays and strings practice, we turn it into three complete programs.
Table of Contents
Before you start. You need three things from the earlier topics. First, the loop template from Branches, conditionals and loops in MIPS: a counter i, a limit n, a beq that leaves when i == n and a j loop that goes back up, with a pointer that moves +4 through a word array. Second, what lw, lh, lb and sll do, from Load, arithmetic and logic in MIPS. Third, reading hexadecimal 2 digits at a time: each pair, like 03 or 4e, is one byte. The topic goes in this order: first, how an array is stored in memory depending on the size of each element and what happens to the sign when you read it; then, indexed access (sll + add + load) and the high score that belonged to AM, properly fixed; next, strings, which are byte arrays with a 0 at the end, and what you do with them (walk them, copy them, turn them into capitals, reverse them); and finally, searches and the symptoms of the mistakes. If you get lost, always go back to the same question: is what I have here an element number or a byte number?
The size sets the step
An array in MIPS is nothing special: it is a label that marks where a bunch of data stored one after another in memory begins. The CPU does not know that “this” is an array. You do, and that is why you decide two things: which instruction reads each element and how far you move to reach the next one. Both depend on the size:
| Directive | Takes | Read with | The pointer moves |
|---|---|---|---|
.word | 4 bytes | lw | +4 |
.half | 2 bytes | lh / lhu | +2 |
.byte | 1 byte | lb / lbu | +1 |
To see it, I stored six players’ lives (3, 0, 1, 5, 2, 4) three times: as words, as halfwords and as bytes. The program adds them up with three identical loops where only the load and the step change:
# sizes.s: the same data in words, halfwords and bytes
.data
vw: .word 3, 0, 1, 5, 2, 4 # lives of 6 players: 4 bytes each
vh: .half 3, 0, 1, 5, 2, 4 # the same: 2 bytes each
vb: .byte 3, 0, 1, 5, 2, 4 # the same: 1 byte each
n: .word 6 # how many players there are
tw: .asciiz "With .word: "
th: .asciiz "\nWith .half: "
tb: .asciiz "\nWith .byte: "
.text
.globl main
main: lw $t1, n # $t1 = 6, the limit of the three loops
# --- word array: lw and +4 ---
la $t0, vw
li $t2, 0 # i = 0
li $s0, 0 # sum = 0
bw: beq $t2, $t1, fw
lw $t3, 0($t0) # 4 bytes
add $s0, $s0, $t3
addi $t0, $t0, 4 # next word
addi $t2, $t2, 1
j bw
fw: li $v0, 4
la $a0, tw
syscall
li $v0, 1
move $a0, $s0
syscall
# --- halfword array: lh and +2 ---
la $t0, vh
li $t2, 0
li $s0, 0
bh: beq $t2, $t1, fh
lh $t3, 0($t0) # 2 bytes
add $s0, $s0, $t3
addi $t0, $t0, 2 # next halfword
addi $t2, $t2, 1
j bh
fh: li $v0, 4
la $a0, th
syscall
li $v0, 1
move $a0, $s0
syscall
# --- byte array: lb and +1 ---
la $t0, vb
li $t2, 0
li $s0, 0
bb: beq $t2, $t1, fb
lb $t3, 0($t0) # 1 byte
add $s0, $s0, $t3
addi $t0, $t0, 1 # next byte
addi $t2, $t2, 1
j bb
fb: li $v0, 4
la $a0, tb
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 10
syscall
Output:
With .word: 15 With .half: 15 With .byte: 15
The three sums are 15 (3 + 0 + 1 + 5 + 2 + 4 = 15), because the data is the same. The interesting part is in memory. This is the data segment as QtSpim shows it:
[10010000] 00000003 00000000 00000001 00000005 . . . . . . . . . . . . . . . . [10010010] 00000002 00000004 00000003 00050001 . . . . . . . . . . . . . . . . [10010020] 00040002 05010003 00000402 00000006 . . . . . . . . . . . . . . . .
Look at the drawing: each row is 4 bytes, and each box is the byte at that address.
Notice three things:
- The same 3 takes 4 bytes, 2 or 1. As a
.wordit is03 00 00 00; as a.half,03 00; as a.byte, just03. That is whyvwtakes 24 bytes,vh12 andvb6. - QtSpim is little endian. The least significant byte goes at the lowest address: the 3 of
vw[0]is at0x10010000with the three zeros after it. In the lecture notes you will read that “real” MIPS is big endian: the simulator uses the byte order of the computer it runs on (yours, a PC). That is why words look “backwards” in the dump: the last word of the second row,00050001, holds the halfwordsvh[2] = 1andvh[3] = 5: the one at the lowest address is on the right. - After
vbthere are 2 padding bytes (the hatched boxes).vbends at0x10010029andnis a.word, so the assembler puts it at the next multiple of 4,0x1001002c. It did it on its own, without being asked.
The array address by address
The QtSpim dump has all the information, but mixed up. Sorted by element it is easier to see. Each array starts where the previous one ends: vw at 0x10010000, vh 24 bytes later (0x10010018) and vb 12 bytes after vh (0x10010024). From there, the address of each element is the start plus whatever the elements in front of it take up:
| Element | Lives | In vw (4 bytes) | In vh (2 bytes) | In vb (1 byte) | Why |
|---|---|---|---|---|---|
| 0 | 3 | 0x10010000 | 0x10010018 | 0x10010024 | It is the start of each array: nothing in front of it |
| 1 | 0 | 0x10010004 | 0x1001001a | 0x10010025 | One element in front: 4, 2 or 1 bytes |
| 2 | 1 | 0x10010008 | 0x1001001c | 0x10010026 | Two in front: 8, 4 or 2 bytes |
| 3 | 5 | 0x1001000c | 0x1001001e | 0x10010027 | Three: 12, 6 or 3 bytes |
| 4 | 2 | 0x10010010 | 0x10010020 | 0x10010028 | Four: 16, 8 or 4 bytes |
| 5 | 4 | 0x10010014 | 0x10010022 | 0x10010029 | Five: 20, 10 or 5 bytes; vb ends here |
Read a whole row: element 3 is 12 bytes after the start in vw, 6 in vh and 3 in vb. It is always the element number times what each element takes up. That is the calculation the pointer does without you seeing it, adding +4, +2 or +1 on every lap, and it is the one you will have to write yourself with sll as soon as you use an index.
The addresses in vw always end in 0, 4, 8 or c (multiples of 4) and those in vh in an even digit (multiples of 2). Those in vb can end in anything. If, while debugging, you see an lw on an address that ends in 1, 2 or 3, you know something is wrong before you even run it.
Copying the template from topic 3 as it is (with lw and +4) for a byte array. With +4 you skip three elements out of four, and with lw you read four numbers glued together as if they were one. The exam cheat sheet has it on the first line of its checklist: “does the pointer step match the data type?”.
Check you’ve got it: if you walk vb with the template from topic 3 (lw and +4), what does it add on the first lap?
It adds 83951619, not 3. The lw on the first lap reads 4 bytes starting at 0x10010024: those of vb[0], vb[1], vb[2] and vb[3], which are 03 00 01 05. Since QtSpim is little endian, the byte at the lowest address is the least significant one, so the word is 0x05010003, the same one you see in the third row of the dump. In decimal, 83951619. The second lap reads at 0x10010028: vb[4], vb[5] and the 2 padding bytes, 0x00000402, which is 1026. Not a single warning: both addresses are multiples of 4, so SPIM does not complain. It only shows in the result.
The sign: lb or lbu, lh or lhu
When you read a byte with lb, the number has to fit in a 32-bit register, so MIPS fills the top 24 bits. The question is with what. We saw it in the load, arithmetic and logic theory, but in an array it shows even more, because the mistake repeats on every lap:
lbandlhextend the sign: they copy the most significant bit.0xFFis read as −1.lbuandlhufill with zeros (the u stands for unsigned).0xFFis read as 255.
A byte array with how many places each player goes up (+) or down (−) in the ranking, added up both ways:
# sign.s: lb or lbu, lh or lhu (the same byte, two numbers)
.data
changes: .byte 2, -1, 0, -3, 1, 1 # places each player goes up (+) or down (-)
penalty: .half -500 # points lost for using a cheat
n: .word 6
t1: .asciiz "Sum with lb: "
t2: .asciiz "\nSum with lbu: "
t3: .asciiz "\nPenalty with lh: "
t4: .asciiz "\nPenalty with lhu: "
.text
.globl main
main: lw $t1, n
la $t0, changes
li $t2, 0 # i = 0
li $s0, 0 # sum with lb
li $s1, 0 # sum with lbu
loop: beq $t2, $t1, end
lb $t3, 0($t0) # signed: 0xff -> -1
lbu $t4, 0($t0) # unsigned: 0xff -> 255
add $s0, $s0, $t3
add $s1, $s1, $t4
addi $t0, $t0, 1 # bytes: +1
addi $t2, $t2, 1
j loop
end: li $v0, 4
la $a0, t1
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, t2
syscall
li $v0, 1
move $a0, $s1
syscall
lh $t5, penalty # signed: 0xfe0c -> -500
lhu $t6, penalty # unsigned: 0xfe0c -> 65036
li $v0, 4
la $a0, t3
syscall
li $v0, 1
move $a0, $t5
syscall
li $v0, 4
la $a0, t4
syscall
li $v0, 1
move $a0, $t6
syscall
li $v0, 10
syscall
Output:
Sum with lb: 0 Sum with lbu: 512 Penalty with lh: -500 Penalty with lhu: 65036
With lb: 2 − 1 + 0 − 3 + 1 + 1 = 0, which is right (in a ranking, the places some players gain, others lose). With lbu, the −1 (0xFF) is read as 255 and the −3 (0xFD) as 253: 2 + 255 + 0 + 253 + 1 + 1 = 512. The halfword does the same: −500 is 0xFE0C, and read as unsigned it is 65036.
Bit by bit, the −3 in changes is the byte 0xFD (1111 1101). What changes is what the 24 bits missing to reach 32 are filled with:
| Instruction | Byte in memory | Fill for the top 24 bits | Register | Value | Why |
|---|---|---|---|---|---|
lb | 0xFD | Ones (a copy of the most significant bit, which is 1) | 0xFFFFFFFD | −3 | With the sign extended, the 32-bit number is the same −3 in two’s complement |
lbu | 0xFD | Zeros | 0x000000FD | 253 | With zeros in front, the top 1 of the byte is worth 128 instead of marking the sign |
The byte is the same in both cases; the instruction decides the result. That is why, in the table below, the question is not “what is in memory?” but “can that byte be negative?”.
When do I use each one? Easy:
| If the value is… | Use | Why |
|---|---|---|
A number that can be negative (.byte -3, .half -500) | lb / lh | You need the sign |
| A character in a string | lbu | A character has no sign; with lbu you never get a negative |
| A number that is never negative and can go over 127 (or 32767) | lbu / lhu | With lb, 200 would be −56 |
The resit cheat sheet uses lb to read characters, and it works with the characters in the labs, because they are ASCII (0 to 127, with the top bit at 0). With lbu it also works with any other byte, so in this topic we use it for strings.
Index versus pointer
So far we walked arrays with a pointer: a register with the address of the current element that moves on every lap. There is another way, the one in the lecture notes: keep the index i (0, 1, 2…) and compute the address when you need it:
address of A[i] = base + i · size
Multiplying by 4 or by 2 is exactly what sll does: shifting 2 bits to the left multiplies by 4, and 1 bit by 2. That is why the pattern is always three instructions: sll (i in bytes), add (plus the base) and the load.
Why sll 2 multiplies by 4
First, in words. In decimal, adding a 0 on the right multiplies by 10: 3 becomes 30. In binary the same happens, but multiplying by 2: every digit moves one place to the left and is worth double. Shifting 2 places is multiplying by 2 twice, that is, by 4. And that is exactly what we need, because the index counts elements and memory counts bytes: to go from “player 3” to “12 bytes from the start”, you have to multiply by what each player takes up.
With the indices of the while below (a word array with its base at 0x10010000):
| i | i in binary | After sll 2 | i · 4 | Address of lives[i] | Why |
|---|---|---|---|---|---|
| 0 | 000 | 00000 | 0 | 0x10010000 | 0 shifted is still 0: the first one is at the base |
| 1 | 001 | 00100 | 4 | 0x10010004 | Two zeros on the right: the 1 is now worth 4 |
| 2 | 010 | 01000 | 8 | 0x10010008 | The 1 moves up two places, from being worth 2 to being worth 8 |
| 3 | 011 | 01100 | 12 | 0x1001000c | 8 + 4 = 12: each 1 is worth 4 times more |
| 4 | 100 | 10000 | 16 | 0x10010010 | Four 4-byte words in front |
| 5 | 101 | 10100 | 20 | 0x10010014 | 16 + 4 = 20, the last of the six |
Why not mul? Because for the hardware shifting is much simpler than multiplying, and the size of the elements is always a power of 2 (4, 2 or 1). So the number in the sll is how many times you multiply by 2: 2 for words, 1 for halfwords and none for bytes.
Check you’ve got it: which sll do you use for the halfword array vh, and why does vb not need one?
For vh, sll $t1, $s3, 1: each element takes 2 bytes and shifting 1 bit multiplies by 2. With i = 3 you get 6, and 0x10010018 + 6 = 0x1001001e, which is the address of vh[3] in the table above. In vb each element takes 1 byte, so the index is already in bytes: i · 1 = i. You save the sll and add directly with add $t1, $s3, $s6. That is why forgetting the sll does not show in byte arrays and does in the rest.
The while (A[i] == k) from the lecture notes
Topic T4.2 has this loop in C: while (A[i] == k) i += 1;, with i in $s3, k in $s5 and the base of A in $s6. I moved it to our arcade: how many players in a row, from the first one, still have the 3 lives they started with?
# index.s: while (lives[i] == k) i = i + 1, as in the lecture notes
.data
lives: .word 3, 3, 3, 1, 3, 0 # each player's lives (words)
k: .word 3 # the lives you start with
txt: .asciiz "Players in a row with all their lives: "
.text
.globl main
main: la $s6, lives # $s6 = base address of the array
lw $s5, k # $s5 = k = 3
li $s3, 0 # $s3 = i = 0
Loop: sll $t1, $s3, 2 # $t1 = i * 4 (each word takes 4 bytes)
add $t1, $t1, $s6 # $t1 = address of lives[i]
lw $t0, 0($t1) # $t0 = lives[i]
bne $t0, $s5, Exit # if lives[i] != k, the while is over
addi $s3, $s3, 1 # i = i + 1
j Loop
Exit: li $v0, 4
la $a0, txt
syscall
li $v0, 1 # print i
move $a0, $s3
syscall
li $v0, 10
syscall
Output:
Players in a row with all their lives: 3
The trace, lap by lap (the base is 0x10010000):
| Lap | i ($s3) | sll → i·4 | Address ($t1) | lives[i] | == 3? |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0x10010000 | 3 | Yes: i = 1 |
| 2 | 1 | 4 | 0x10010004 | 3 | Yes: i = 2 |
| 3 | 2 | 8 | 0x10010008 | 3 | Yes: i = 3 |
| 4 | 3 | 12 | 0x1001000c | 1 | No: bne to Exit |
It leaves with i = 3: the first three players have their three lives. Notice that this loop has no counter and no limit: it only stops when it finds an element different from k. If all six players had 3 lives, it would keep reading whatever comes after the array. In the lecture notes it is written that way because it is a C example; in your programs, add the stop at n unless you are sure the loop will find something that ends it.
One index, two sizes: the high score done right
Back to the high score that belonged to AM. The scores are halfwords (2 bytes) and each name takes 4 bytes, so the same index becomes a different offset in each array: i · 2 in one, i · 4 in the other. This is the fixed version, which also walks the scores by index so you see the pattern twice:
# record.s: the same index, two different sizes
.data
scores: .half 9850, 15600, 7320, 12400, 11050, 8800 # 6 high scores, one halfword each
n: .word 6
names: .asciiz "SAM", "LEO", "ANA", "MAX", "ZOE", "KAI" # 4 bytes per name
txt1: .asciiz "Record: "
txt2: .asciiz " with "
txt3: .asciiz " points\n"
.text
.globl main
main: la $s2, scores # base of the scores
lw $t1, n
li $t2, 0 # i = 0
li $s0, -1 # maximum
li $s1, 0 # position of the maximum
loop: beq $t2, $t1, end
sll $t4, $t2, 1 # $t4 = i * 2 (halfword)
add $t4, $t4, $s2 # $t4 = address of scores[i]
lh $t3, 0($t4) # $t3 = scores[i]
ble $t3, $s0, next
move $s0, $t3 # new maximum
move $s1, $t2 # and its position
next: addi $t2, $t2, 1 # with an index only i moves on
j loop
end: li $v0, 4
la $a0, txt1
syscall
sll $t5, $s1, 2 # position * 4 (each name takes 4 bytes)
la $a0, names
add $a0, $a0, $t5 # $a0 = address of names[position]
li $v0, 4
syscall
li $v0, 4
la $a0, txt2
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, txt3
syscall
li $v0, 10
syscall
Output:
Record: LEO with 15600 points
Now it is LEO. The two conversions from index to bytes, side by side:
sll $t4, $t2, 1 # $t4 = i * 2 (halfword) add $t4, $t4, $s2 # $t4 = address of scores[i] lh $t3, 0($t4) # $t3 = scores[i]
sll $t5, $s1, 2 # position * 4 (each name takes 4 bytes) la $a0, names add $a0, $a0, $t5 # $a0 = address of names[position]
In the first one, sll ..., 1 multiplies by 2 (scores); in the second, sll ..., 2 multiplies by 4 (names). The drawing shows where each address lands and why hook.s printed AM:
And the data segment, where you can see the names packed 4 by 4 (SAM., LEO., ANA.…):
[10010000] 3cf0267a 30701c98 22602b2a 00000006 z & . < . . p 0 * + ` " . . . . [10010010] 004d4153 004f454c 00414e41 0058414d S A M . L E O . A N A . M A X . [10010020] 00454f5a 0049414b 6f636552 203a6472 Z O E . K A I . R e c o r d :
The first three words are the six high scores: 3cf0267a is 0x267a = 9850 (the one at the lowest address, on the right) and 0x3cf0 = 15600. n = 6 is at 0x1001000c and the names start at 0x10010010.
The high-score trace, lap by lap
With the table in front of you, you can see where the AM got fixed. In the loop, $t4 moves 2 by 2 even though i moves 1 by 1, because sll $t4, $t2, 1 turns each i into halfword bytes:
| Lap | i ($t2) | i · 2 | Address ($t4) | scores[i] | Beats the maximum? | Maximum ($s0) | Position ($s1) |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 0x10010000 | 9850 | Yes (9850 > −1) | 9850 | 0 |
| 2 | 1 | 2 | 0x10010002 | 15600 | Yes (15600 > 9850) | 15600 | 1 |
| 3 | 2 | 4 | 0x10010004 | 7320 | No | 15600 | 1 |
| 4 | 3 | 6 | 0x10010006 | 12400 | No | 15600 | 1 |
| 5 | 4 | 8 | 0x10010008 | 11050 | No | 15600 | 1 |
| 6 | 5 | 10 | 0x1001000a | 8800 | No | 15600 | 1 |
| 7 | 6 | beq: i == n, to end | 15600 | 1 |
On the way out, the position is 1. Now the two versions of the ending, side by side:
| Program | Calculation | $a0 | What syscall 4 prints | Why |
|---|---|---|---|---|
hook.s | 0x10010010 + 1 | 0x10010011 | AM | It lands on the A of SAM and reads up to its '\0' |
record.s | 0x10010010 + 1 · 4 | 0x10010014 | LEO | It skips a whole name, 4 bytes |
The position is the same in both programs; the only difference is whether it is turned into bytes before adding it.
Adding the index without scaling it. With a byte array it works (multiplying by 1 changes nothing), and that is misleading: you copy the code to a word array and it stops working. With lw it also raises an exception, because the address is no longer a multiple of 4:
# nosll.s: the index without scaling in a word array
.data
lives: .word 3, 3, 3, 1, 3, 0
.text
.globl main
main: la $s6, lives
li $s3, 1 # i = 1: I want lives[1]
add $t1, $s3, $s6 # the sll is missing: base + 1, not base + 4
lw $t0, 0($t1) # lw at an address that is not a multiple of 4
li $v0, 1
move $a0, $t0
syscall
li $v0, 10
syscall
Console:
Exception 4 [Address error in inst/data fetch] occurred and ignored 0
And in the messages window:
Exception occurred at PC=0x00400030 Unaligned address in inst/data fetch: 0x10010001
Unaligned address: lw can only read at addresses that are a multiple of 4, and 0x10010001 is not. The 0 printed afterwards is whatever was left in $t0, because SPIM ignores the exception and carries on. lh does the same at odd addresses; lb and lbu never do, because any address is fine for a byte.
When do I use an index and when a pointer?
| I want to… | Better with | Why |
|---|---|---|
| Walk a whole array from start to end | Pointer | One addition per lap and no multiplication |
Use the position i for something (print the place, even positions) | Index | You already have i and you use it to compute |
| Read two arrays “in parallel” with different sizes | Index | One i and a different sll for each |
Reach a specific position (A[5], the maximum’s) | Index | You compute the address directly |
| Walk a string | Pointer | You do not know the length: you move until the '\0' |
Both are fine in the exam. What is not fine is mixing them halfway: if you use an index, the pointer does not move; if you use a pointer, do not multiply anything.
Strings: characters that end in ‘\0’
A string is a byte array with one rule: it ends with a byte set to 0, the '\0'. With .asciiz "INSERT COIN" the assembler stores the 11 ASCII codes and adds the 0 (the z in asciiz stands for zero). With .ascii it does not, and then it is up to you.
That '\0' is what lets you walk a string without knowing its length: you move 1 by 1 until the byte you read is 0. And it is what syscall 4 uses: it prints from $a0 up to the first 0. This program counts the characters of the arcade’s message:
# string.s: walk a string up to its '\0'
.data
msg: .asciiz "INSERT COIN" # 11 characters + the '\0'
txt: .asciiz " has "
txt2: .asciiz " characters\n"
.text
.globl main
main: la $t0, msg # pointer to the first character
li $s0, 0 # length = 0
loop: lbu $t1, 0($t0) # $t1 = current character (unsigned)
beqz $t1, end # if it is the '\0', the string is over
addi $s0, $s0, 1 # length = length + 1
addi $t0, $t0, 1 # next character (1 byte)
j loop
end: li $v0, 4
la $a0, msg
syscall
li $v0, 4
la $a0, txt
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, txt2
syscall
li $v0, 10
syscall
Output:
INSERT COIN has 11 characters
This is the string loop you will use in almost the whole topic. Compare it with the template from topic 3: there is no index and no limit n. The stop is the data itself: lbu reads the character and beqz (branch if zero) ends the loop. And the step is +1, because a character is one byte.
The string, byte by byte
This is how the loop in string.s goes over "INSERT COIN", which starts at 0x10010000:
| Lap | $t0 | Byte read ($t1) | Character | Does beqz branch? | Length ($s0) |
|---|---|---|---|---|---|
| 1 | 0x10010000 | 0x49 | I | No | 1 |
| 2 | 0x10010001 | 0x4e | N | No | 2 |
| 3 | 0x10010002 | 0x53 | S | No | 3 |
| 4 | 0x10010003 | 0x45 | E | No | 4 |
| 5 | 0x10010004 | 0x52 | R | No | 5 |
| 6 | 0x10010005 | 0x54 | T | No | 6 |
| 7 | 0x10010006 | 0x20 | (space) | No | 7 |
| 8 | 0x10010007 | 0x43 | C | No | 8 |
| 9 | 0x10010008 | 0x4f | O | No | 9 |
| 10 | 0x10010009 | 0x49 | I | No | 10 |
| 11 | 0x1001000a | 0x4e | N | No | 11 |
| 12 | 0x1001000b | 0x00 | '\0' | Yes, to end | 11 |
Notice two things. The space does not stop the loop: it is worth 32, not 0, and it counts as one more character. And on lap 12 the '\0' is read but not counted, because beqz branches before the addi $s0, $s0, 1. That is why there are 12 reads and the length is 11.
Reading the string with lw instead of lbu. The lw on the first lap takes the first 4 characters at once, 0x45534e49 (1163087433): it is not a letter, it is four stuck together. beqz would only branch if all four bytes were 0, so the '\0' slips past if it has company. And if you move +1, the second lw lands on 0x10010001, which is not a multiple of 4: Unaligned address. With +4 there is no warning, but this program says 8, which are words and not characters. In a string, a character is a byte: lbu and +1.
Check you’ve got it: what does string.s print if you change .asciiz to .ascii in msg?
It prints INSERT COIN has has 16 characters. With .ascii there is no '\0' after INSERT COIN, so txt, " has ", already starts at 0x1001000b. The loop sees no 0 after the N and keeps counting the 5 characters of " has " up to its '\0': 11 + 5 = 16. Syscall 4 does the same when printing msg: it does not stop until the first 0, so it prints " has " as well, and then the program prints txt again. That is why has comes out twice. A string ends where its '\0' is, not where what you wrote between the quotes ends.
The memory:
[10010000] 45534e49 43205452 004e494f 73616820 I N S E R T C O I N . h a s [10010010] 63200020 61726168 72657463 00000a73 . c h a r a c t e r s . . .
The first word, 45534e49, is the bytes 49 4e 53 45: I, N, S, E. Little endian again: in the right-hand column QtSpim shows the characters in their real order, which is the one that matters to you. The 00 in 004e494f (third word, leftmost byte) is the '\0' of INSERT COIN, at 0x1001000b, and the next byte is already the start of " has ".
The ASCII table you need for the exam fits in three lines: space = 32 (0x20), '0'…'9' = 48…57 (0x30…0x39), 'A'…'Z' = 65…90 (0x41…0x5A) and 'a'…'z' = 97…122 (0x61…0x7A). And you do not even have to learn it: SPIM understands characters in single quotes, so you can write blt $t2, 'a', ... or li $a0, ' ' instead of 97 or 32.
Writing into another string: two pointers and sb $zero
Loads of exercises (and the 2025 practical exam) ask you to read a string and build another one: copy it, change letters, reverse it, remove something. You need two things for that:
- Room for the new string, reserved with
.space N(N bytes set to zero). Pick an N with room to spare: the length of the original plus 1 for the'\0', at least. - Two pointers: a read pointer (in the original) and a write pointer (in the new one), and
sbto store each character.
The simplest copy, the one the lecture notes call strcpy (there as a subroutine, which we will see in topic 6):
# copy.s: copy one string into another with two pointers
.data
title: .asciiz "SPACE MIPS" # the original string
copy: .space 16 # room for the copy (16 zero bytes)
txt: .asciiz "Copy: "
.text
.globl main
main: la $t0, title # read pointer
la $t1, copy # write pointer
loop: lbu $t2, 0($t0) # read a character
beqz $t2, end # if it is the '\0', stop
sb $t2, 0($t1) # write it into the copy
addi $t0, $t0, 1 # both pointers move on
addi $t1, $t1, 1
j loop
end: sb $zero, 0($t1) # close the copy with its '\0'
li $v0, 4
la $a0, txt
syscall
li $v0, 4
la $a0, copy
syscall
li $v0, 10
syscall
Output:
Copy: SPACE MIPS
Look at the order inside the loop: first lbu, then beqz, and only then sb. That way, when the character read is the '\0', the loop leaves before writing it. That is why the sb $zero, 0($t1) after the loop is needed: it closes the copy with its own '\0'. The $zero register is always 0, so sb $zero writes exactly one byte set to 0.
And if you forget it? In this program you would not notice, because .space 16 reserves bytes that are already 0. But if the new string reuses a place that already had something written in it (you will see it in “What’s wrong here?” in the exercises), the copy “carries on” with whatever was behind it. Always close it: it is the second line of the cheat sheet’s checklist.
Transforming characters
Since a character is a number, transforming it is doing a sum. To turn it into a capital, look at the ASCII table: 'a' is 97 and 'A' is 65. Between each lowercase letter and its capital there are 32. So addi $t2, $t2, -32 turns 'a' into 'A', 'b' into 'B'… But only if the character is a lowercase letter. If you subtract 32 from a space (32), you get a 0, and that is a '\0' in the middle of your string.
The condition “is lowercase” is an “and” like the ones in topic 3: c >= 'a' and c <= 'z'. With the opposite condition, either one that fails jumps to write the character untouched:
# upper.s: the nickname in capitals (only the letters from a to z)
.data
nick: .asciiz "leo_99 wins" # the original string
big: .space 16 # the new string
txt: .asciiz "Nick: "
.text
.globl main
main: la $t0, nick # read pointer
la $t1, big # write pointer
loop: lbu $t2, 0($t0)
beqz $t2, end
blt $t2, 'a', store # opposite of (c >= 'a'): not lowercase
bgt $t2, 'z', store # opposite of (c <= 'z'): not lowercase
addi $t2, $t2, -32 # 'a' (97) - 32 = 'A' (65)
store: sb $t2, 0($t1) # write the character (changed or not)
addi $t0, $t0, 1
addi $t1, $t1, 1
j loop
end: sb $zero, 0($t1) # close the new string
li $v0, 4
la $a0, txt
syscall
li $v0, 4
la $a0, big
syscall
li $v0, 10
syscall
Output:
Nick: LEO_99 WINS
The _, the digits and the space go through as they are; the seven lowercase letters become capitals. The two blt/bgt with a character are pseudo-instructions: the assembler turns them into slti $at, $t2, 97 + bne (and slti $at, $t2, 123 + beq), as we saw in topic 3.
In topic 2 we saw another way: andi $t2, $t2, 0xDF clears bit 5 (the one worth 32) and also turns lowercase into capitals. It has the same problem: it is only safe if you have checked first that it is a lowercase letter. Use whichever you understand better; the exam values that it works “for any string”.
To print a single character there is syscall 11 (print_char): put the character in $a0, li $v0, 11 and syscall. It needs no '\0' and no address. We will use it in the practice to light up the sign letter by letter.
Reversing a string
Reversing is the most typical string exercise (labs 6.18 and 6.19 are about it), and it has one detail you have to think about: to read backwards you need to know where the string ends. So there are four steps:
- Find the end: a pointer moves up to the
'\0'. - Step back one, to sit on the real last letter.
- Copy with reading going backwards (−1) and writing going forwards (+1), until reading goes past the start.
- Close the new one with
sb $zero.
# reverse.s: the string backwards, into another string
.data
brand: .asciiz "ATARI"
reversed: .space 16
txt: .asciiz " backwards: "
.text
.globl main
main: la $t0, brand # $t0 = start of the string
move $t1, $t0 # $t1 will look for the '\0'
find: lbu $t2, 0($t1)
beqz $t2, back # $t1 points to the '\0'
addi $t1, $t1, 1
j find
back: addi $t1, $t1, -1 # the real last character (not the '\0')
la $t3, reversed # write pointer
copy: blt $t1, $t0, end # if I have gone past the start, stop
lbu $t2, 0($t1)
sb $t2, 0($t3)
addi $t1, $t1, -1 # reading goes backwards
addi $t3, $t3, 1 # writing, forwards
j copy
end: sb $zero, 0($t3) # close the reversed string
li $v0, 4
la $a0, brand
syscall
li $v0, 4
la $a0, txt
syscall
li $v0, 4
la $a0, reversed
syscall
li $v0, 10
syscall
Output:
ATARI backwards: IRATA
The copy stops at blt $t1, $t0, end: we are comparing addresses. When $t1 (reading) drops below $t0 (the start), we have already copied the A at position 0. Comparing addresses with blt is perfectly valid: they are numbers.
Skipping step 2. If you start copying from the '\0', the first thing you write into the new string is a 0, and syscall 4 prints… nothing. It is snippet 3 in the exercises.
Searching an array
Searches are the other family of exercises. You have already seen one: the maximum and its position (in record.s), which keeps the highest value and the i where it was. The other one is the first occurrence: at which position is the first player with no lives left? If there is none, the answer is −1 (a position that does not exist):
# search.s: the first occurrence of a value (or -1 if it is not there)
.data
lives: .byte 3, 1, 0, 5, 0, 2 # each player's lives
n: .word 6
targets: .byte 0, 9 # search for 0 first and then for 9
txt1: .asciiz "First player with "
txt2: .asciiz " lives: "
nl: .asciiz "\n"
.text
.globl main
main: lw $t1, n
la $s2, targets # pointer to what I am looking for
li $s3, 0 # search number 0
other: beq $s3, 2, quit # two searches
lb $s4, 0($s2) # $s4 = value searched for
li $s0, -1 # position = -1 (not found)
la $t0, lives
li $t2, 0 # i = 0
loop: beq $t2, $t1, end # walked it all: not there
lb $t3, 0($t0)
bne $t3, $s4, next # opposite of (lives[i] == target)
move $s0, $t2 # found it at i
j end # and stop: I only want the first one
next: addi $t0, $t0, 1
addi $t2, $t2, 1
j loop
end: li $v0, 4
la $a0, txt1
syscall
li $v0, 1
move $a0, $s4
syscall
li $v0, 4
la $a0, txt2
syscall
li $v0, 1
move $a0, $s0
syscall
li $v0, 4
la $a0, nl
syscall
addi $s2, $s2, 1 # next value to search for
addi $s3, $s3, 1
j other
quit: li $v0, 10
syscall
Output:
First player with 0 lives: 2 First player with 9 lives: -1
The 0 appears at positions 2 and 4, and the program says 2: the first one. The 9 is not there, and it prints −1. The key is in two lines:
li $s0, -1before the loop: if the loop ends without finding anything, the position stays at −1.j endright aftermove $s0, $t2: as soon as it finds it, it leaves. Without that jump, the loop would carry on and every later 0 would overwrite the position: you would end up with the last occurrence, not the first.
| I want… | I start with | Inside the loop | When found |
|---|---|---|---|
| Maximum and position | max = −1 (or the first element) | if x > max: max = x, pos = i | Keep going to the end |
| First occurrence | pos = −1 | if x == target | pos = i and leave with j |
| Last occurrence | pos = −1 | if x == target | pos = i and keep going |
| Count occurrences | count = 0 | if x == target | count + 1 and keep going |
For the maximum we start at −1 because all the high scores are positive. If the array can hold negatives, start with the first element and walk from the second one. It is safer “for any array”, which is what the exam statement asks for.
When SPIM complains (and when it does not)
The mistakes in this topic have one thing in common: most of them give no message at all. The program ends and the output is wrong. That is why this table is about symptoms:
| Symptom | Likely cause |
|---|---|
| Unaligned address in inst/data fetch | lw/lh at an address that is not a multiple of 4 (or 2): the sll is missing or the pointer moves wrongly |
| Part of another name is printed (“AM”) | Index not scaled in an array whose elements are bigger than 1 byte |
| A sum of bytes comes out huge (512 instead of 0) | lbu with negative numbers: use lb |
| The new string is cut at the first space | You subtracted 32 from everything, the space too (32 − 32 = 0) |
| The new string has “garbage” at the end | The sb $zero is missing and the place already had something written in it |
| The reversed string comes out empty | You started copying from the '\0' (the addi -1 is missing) |
| The character count is odd (8 instead of 11) | You move +4 in a string: you read one in four and skip the '\0' |
| Bad address in data/stack read | The loop runs out of the data segment: it never finds its stop ('\0' or n) |
Reading an array that is not made of words with lw. Sometimes SPIM warns you and sometimes it does not, and that makes it worse. In vh, the word at 0x1001001c (a multiple of 4) joins vh[2] and vh[3]: lw returns 0x00050001, which is 327681, without any message. At 0x1001001a (not a multiple of 4) it would give Unaligned address. The rule to avoid it: before writing the load, look at the array’s directive. .word means lw and +4 (or sll 2); .half, lh and +2 (or sll 1); .byte and strings, lb/lbu and +1, with no sll.
Check you’ve got it: in hook.s, why did SPIM not give Unaligned address if the name’s address was wrong?
Because the name is loaded by syscall 4, which reads byte by byte up to the '\0', and any address is fine for a byte. 0x10010011 is not a multiple of 4, but nobody did an lw on it. If instead of printing the name you had read its 4 bytes with lw $t0, 0($a0), Unaligned address would have gone off. That is why the high score that belonged to AM is the worst kind of mistake: no sll and no lw, so the only symptom is a name that does not exist.
Try it in QtSpim (or right here)
Arrays and strings make sense when you look at the data tab. Open QtSpim (or the environment below, which works the same way) with the high-score table:
Loading the MIPS environment… If it does not appear, copy record.s into your QtSpim.
- Before running, look at the Data tab: the names start at
0x10010010, and in the right-hand column you can readS A M . L E O . A N A .. Each dot is a'\0'. - Run step by step with F10 and watch
$t4on every lap:0x10010000,0x10010002,0x10010004… it moves 2 by 2 even though$t2(the index) moves 1 by 1. - In the last part, after
sll $t5, $s1, 2,$t5is 4: position 1 turned into bytes. And$a0ends up at0x10010014, the start of LEO. - Change
sll $t5, $s1, 2tosll $t5, $s1, 1and run it: the name comes out cut again, because now you multiply by the size of the scores, not the size of the names. - Change
lhtolband run it: the scores are read wrongly, becauselbonly takes the least significant byte of each halfword.
Summary
| Concept | The essentials |
|---|---|
| Size | .word = 4 bytes (lw, +4), .half = 2 (lh, +2), .byte = 1 (lb, +1) |
| Sign | lb/lh extend the sign; lbu/lhu fill with zeros. Characters: lbu |
| Index | address = base + i · size: sll (×4 with 2, ×2 with 1) + add + load |
| Alignment | lw needs a multiple of 4 and lh of 2; otherwise, Unaligned address |
| String | Bytes ending in '\0'; walked with lbu + beqz and a +1 step |
| Writing another string | .space N, two pointers, sb in the loop and sb $zero at the end |
| Capitals | If 'a' <= c <= 'z': c − 32 (never to everything) |
| Reverse | Find the '\0', step back one, read −1 and write +1, close |
| Search | Maximum: walk it all; first occurrence: pos = −1 and leave with j when found |
Three ideas to take away
- The index counts elements and memory counts bytes. To go from one to the other, multiply by the size (
sll). The sameigives different offsets in different arrays. - A string ends where its
'\0'is, not where you think: walk it up to that byte withlbu+beqzand, if you build a new one, close it yourself withsb $zero. - Check first, transform afterwards: subtracting 32, changing or counting is only done to the characters that meet the condition; the rest is copied as it is.
In the arrays and strings practice we turn the arcade into three complete programs: the high-score table with one index for two arrays, the sign that lights up in capitals letter by letter and a mirror that turns messages round and looks for palindrome names.
Next step: practiceArrays and strings in MIPS — practice in QtSpim: the high-score table, a sign that lights up in capitals and a mirror for messages (and the sign that went dark at the first space)Did this article help you? Here is how you can support SergioLearns →



