Sikau

Assembly language · Day 4 · about 40 min

Memory: load and store

The .data section, addresses, lw and sw, and walking through an array.

32 registers aren't enough

Real data lives in memory: a long row of bytes, each with an address. You can't add memory directly — load a value into a register (lw), work on it, and store it back (sw). A word is 4 bytes, so element *i* of a word array is at address + i × 4.

.data
nums: .word 12, -5, 40, 7, 40, 3

.text
# max(a0 = address of words, a1 = how many) -> a0 = the largest
max:
  lw   t0, 0(a0)      # best so far = first word
  li   t1, 1          # i = 1
next:
  bge  t1, a1, finish
  slli t2, t1, 2      # byte offset = i * 4
  add  t2, a0, t2
  lw   t3, 0(t2)
  ble  t3, t0, skip
  mv   t0, t3
skip:
  addi t1, t1, 1
  j    next
finish:
  mv   a0, t0
  ret

Addressing

  • lw t0, 8(a0) loads the word at a0 + 8 (the third element).
  • sw t0, 0(a1) stores t0's word at the address in a1.
  • lb/sb work with single bytes (characters).
  • Addresses of words must be multiples of 4 — otherwise it's a misaligned access.

Memory is a street of houses numbered by byte. A word is a four-house plot: plot i of a row that starts at 2000 begins at house 2000 + 4i.

The rest of this lesson

  • Walking an array with a pointerexplain
  • Bytes, words and signsexplain
  • Which element?predict
  • Pick the loadmatch
  • Find the maximumwrite code
  • Badge quizquiz
  • Unit 1 completerecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Assembly language