Sikau

Assembly language · Day 2 · about 35 min

Arithmetic and functions

addi, sub, mul, div and rem — and your first function with arguments in a0.

A function is just a label

There's no function keyword in assembly. A function is a label to jump to; by convention its arguments arrive in a0, a1…, it leaves results in a0, a1…, and ret jumps back to whoever called it.

# split(a0 = total seconds) -> a0 = hours, a1 = minutes, a2 = seconds
split:
  li   t0, 3600
  div  t1, a0, t0     # hours
  rem  t2, a0, t0     # seconds left after the hours
  li   t0, 60
  div  a1, t2, t0     # minutes
  rem  a2, t2, t0     # seconds
  mv   a0, t1
  ret

The arithmetic instructions

  • add, sub, mul, div, rem take three registers.
  • addi t0, t0, 1 adds a small constant (there's no subi — use a negative number).
  • mv a0, t1 copies a register.
  • Values are 32-bit and wrap around on overflow, just like in the ALU you built.

The rest of this lesson

  • Division and remaindersexplain
  • Small constants and big onesexplain
  • Average of twofill
  • Instruction to meaningmatch
  • Write a functionwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Assembly language