---
title: Assembly lab
heading: Five small routines, written and tested on the board
eyebrow: C8 · Lesson 19 · Assembly lab
xp: 50
---

::: hook
Reading assembly and writing it are different skills, and the second only comes from practice. This lab is five routines of the kind every embedded programmer writes: find the largest value in an array, copy a block of memory, reverse a string in place, count the 1 bits in a word, and find a greatest common divisor. Each one is run on the simulated board and checked against your own numbers, so a routine that works for one input but not another will be caught.
:::

::: play
- A worked routine to study before you start: it finds the largest of six signed words. A pointer walks the array; a0 holds the largest so far and is replaced whenever a bigger value turns up.
- Step it and watch a0 change only at the 27s. Notice that `ble` compares as signed numbers, so −3 is correctly smaller than 14.
:::
:::

```sim cpu
.data
vals: .word 14, -3, 27, 8, 27, 19
.text
    la t0, vals
    li t1, 6
    lw a0, 0(t0)
loop:
    addi t0, t0, 4
    addi t1, t1, -1
    beqz t1, done
    lw t2, 0(t0)
    ble t2, a0, loop
    mv a0, t2
    j loop
done:
    ebreak
show: a0, t1, t2
hex: t0
memory: 0x1000..0x1018
speed: 4
```

::: predict
## A routine counts the 1 bits in a word by testing the lowest bit and shifting right, 32 times. A faster trick clears the lowest set bit each pass with `x & (x − 1)`. How many passes does that take for 0x00000081?

- [ ] 32
- [ ] 8
- [x] 2
- [ ] 1

::: reveal
2: 0x81 has two 1 bits, and each `x & (x − 1)` clears exactly one of them. The loop runs once per set bit instead of once per bit position.
:::
:::

::: nameit
## Patterns you'll use

- **Running maximum:** load the first element, then compare each next one and replace when larger (signed branches for signed data).
- **Block copy:** two pointers and a counter; load from one, store to the other, advance both.
- **In-place reversal:** a pointer at each end; swap the two bytes and move the pointers toward each other until they meet.
- **Bit counting:** `andi t0, x, 1` reads the lowest bit; `srli x, x, 1` moves the next one down. Or clear the lowest set bit with `addi t0, x, -1` and `and x, x, t0`, counting passes until x is 0.
- **Euclid's algorithm:** gcd(a, b) is unchanged when the larger is replaced by the difference; repeat until they're equal. (With remainder, `rem`, it converges faster.)

## Testing

Each task below runs your code with values set before it starts and checks registers or memory when it reaches `ebreak`. Data labels start at 0x1000: the first `.data` item is at 0x1000, the next word at 0x1004, and so on.
:::

::: example
## Trace the block copy of three words from `src` to `dst`.

::: solution
1. **Copy one word.** Load src[0] and store it to dst[0].
2. **Advance.** Move both pointers on by 4 and the count down by 1.
3. **Repeat.** Go again while the count is above 0.
4. **After three passes.** dst holds the same three words, and both pointers sit just past their blocks.

**Answer:** three passes copy the three words, leaving both pointers just past their blocks.
:::
:::

::: example
## Reverse "abc" in place.

::: solution
1. **Start at the ends.** The pointers are at 'a' (address 0) and 'c' (address 2).
2. **Swap.** That gives "cba".
3. **Move inward.** The pointers move to 1 and 1. They've met, so stop.
4. **The middle character.** It never moves.

**Answer:** one swap turns "abc" into "cba".
:::
:::

::: check
kind: asm
given: a = 1..90 int; b = -90..90 int; c = -90..90 int; d = -90..-1 int; e = -90..90 int
expect: a0 = (((a + b + abs(a - b))/2 + c + abs((a + b + abs(a - b))/2 - c))/2 + (d + e + abs(d - e))/2 + abs(((a + b + abs(a - b))/2 + c + abs((a + b + abs(a - b))/2 - c))/2 - (d + e + abs(d - e))/2))/2

## Leave the largest of the five signed words in `vals` in a0.

```asm starter
.data
vals: .word a, b, c, d, e
.text
    la t0, vals
    ebreak
```

```asm solution
.data
vals: .word a, b, c, d, e
.text
    la t0, vals
    li t1, 5
    lw a0, 0(t0)
loop:
    addi t0, t0, 4
    addi t1, t1, -1
    beqz t1, done
    lw t2, 0(t0)
    ble t2, a0, loop
    mv a0, t2
    j loop
done:
    ebreak
```

::: right
Right. Signed comparisons, so negative values are handled.
:::
:::

::: check
kind: asm
given: p = 1..999 int; q = 1..999 int; r = 1..999 int
expect: mem[0x100C] = p; mem[0x1010] = q; mem[0x1014] = r

## Copy the three words at `src` to `dst` (src is at 0x1000, dst at 0x100C).

```asm starter
.data
src: .word p, q, r
dst: .word 0, 0, 0
.text
    la t0, src
    la t1, dst
    ebreak
```

```asm solution
.data
src: .word p, q, r
dst: .word 0, 0, 0
.text
    la t0, src
    la t1, dst
    li t2, 3
loop:
    beqz t2, done
    lw t3, 0(t0)
    sw t3, 0(t1)
    addi t0, t0, 4
    addi t1, t1, 4
    addi t2, t2, -1
    j loop
done:
    ebreak
```

::: right
Right. Two pointers moving together, and a counter.
:::
:::

::: check
kind: asm
expect: byte[0x1000] = 115; byte[0x1001] = 109; byte[0x1002] = 104; byte[0x1003] = 79

## Reverse the 4-character string `word` ("Ohms", at 0x1000) in place, so it reads "smhO".

```asm starter
.data
word: .asciz "Ohms"
.text
    la t0, word
    ebreak
```

```asm solution
.data
word: .asciz "Ohms"
.text
    la t0, word
    addi t1, t0, 3
loop:
    bgeu t0, t1, done
    lbu t2, 0(t0)
    lbu t3, 0(t1)
    sb t3, 0(t0)
    sb t2, 0(t1)
    addi t0, t0, 1
    addi t1, t1, -1
    j loop
done:
    ebreak
```

::: right
Right. Swap from the ends inward; stop when the pointers meet or cross.
:::
:::

::: check
kind: asm
given: n = 1..255 int
setup: a0 = n
expect: a1 = (n - 2*floor(n/2)) + (floor(n/2) - 2*floor(n/4)) + (floor(n/4) - 2*floor(n/8)) + (floor(n/8) - 2*floor(n/16)) + (floor(n/16) - 2*floor(n/32)) + (floor(n/32) - 2*floor(n/64)) + (floor(n/64) - 2*floor(n/128)) + floor(n/128)

## Count the 1 bits in a0 (an 8-bit value) and leave the count in a1.

```asm starter
    # the value is in a0
    li a1, 0
    ebreak
```

```asm solution
    li a1, 0
loop:
    beqz a0, done
    addi t0, a0, -1
    and a0, a0, t0      # clear the lowest set bit
    addi a1, a1, 1
    j loop
done:
    ebreak
```

::: right
Right. However you did it, testing bits or clearing the lowest one, the count matches.
:::
:::

::: check
kind: asm
given: g = 2..40 int; p = 3 | 5 | 7; q = 4 | 8 | 11; let a = g*p; let b = g*q
setup: a0 = a; a1 = b
expect: a0 = g

## a0 and a1 hold two positive numbers. Leave their greatest common divisor in a0.

```asm starter
    # the numbers are in a0 and a1
    ebreak
```

```asm solution
loop:
    beq a0, a1, done
    blt a0, a1, smaller
    sub a0, a0, a1
    j loop
smaller:
    sub a1, a1, a0
    j loop
done:
    ebreak
```

::: right
Right. Subtracting the smaller from the larger keeps the GCD, and they meet at it.
:::
:::

::: explain
## Why does clearing the lowest set bit with `x & (x - 1)` work?

::: model
Subtracting 1 from a binary number turns its lowest 1 bit into a 0 and every 0 below it into a 1, leaving the higher bits unchanged. ANDing that with the original keeps the higher bits (they're the same in both) and clears everything from the lowest 1 bit down, since in those positions one of the two numbers has a 0. So each pass removes exactly one 1 bit, and a loop counts the 1s in as many passes as there are 1s.
:::
:::

::: practice

::: check
given: n = 1..255 int
answer: n - 2*floor(n/2)
tolerance: 0

## What does `andi t0, a0, 1` leave in t0 when a0 = {n}?

::: misses
- [any] The lowest bit.
:::
:::

::: check
given: k = 3 | 4 | 7
answer: 4096 + 4*k
base: 16
width: 4

## A `.data` section starts at 0x1000 with a list of words. Where is word {k} (counting from 0)?

::: misses
- [any] 0x1000 + 4k.
:::
:::

::: check
given: a = 12 | 30 | 84; b = 18 | 45 | 126
answer: a + b - 1
tolerance: 0

## For two positive numbers {a} and {b}, what is the most subtraction steps Euclid's algorithm by subtraction could possibly need (a loose bound: a + b − 1)?

::: misses
- [any] Each step reduces a + b by at least 1.
:::
:::
:::
