Sikau

How computers work · Day 11 · about 40 min

Programming the machine

Loops, multiplication and Fibonacci in machine instructions.

No multiply button

Our CPU can't multiply. Neither could early chips. You can still compute 6 × 7 — add 6 seven times, with a counter and a jump. This is what compilers turn your JavaScript into: registers, arithmetic and jumps.

Patterns in machine code

  • Counted loop: load a counter, do the work, DEC the counter, JNZ back to the start.
  • Temporary register: to swap or combine values, copy one aside with MOV first.
  • Addresses: jump targets are positions in the program (0 = first instruction).

The full instruction set now also has MOV r s (copy), INC r, DEC r and JNZ r n (jump if not zero). ADD and SUB accept a register or a number.

0: LOAD A 5
1: OUT A
2: DEC A
3: JNZ A 1
4: HALT

The rest of this lesson

  • Multiplying with a loopexplain
  • From JavaScript to instructionsexplain
  • Trace the looppredict
  • Finish the countdownfill
  • Three programswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work