学び直し19日目:4章 機械語⑤
記録
機械語で掛け算を書いた。考え方としては、「R0 の値を R1 の値の回数だけ足して、都度 R2 を更新する」というもの。まさに掛け算の考え方。自力ではちょっと厳しかったので、先人のコードを拝見しながら書きつつ、エミュレーターうごかしたらなんとなくわかってきました。ほんとにコンピューターって、ロジックの積み重ねなんだなぁ。
github.com
IO操作はまた明日。
mult.am
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/04/Mult.asm // Multiplies R0 and R1 and stores the result in R2. // (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.) // Put your code here. // Initialize R2 @R2 M = 0 // Basic concept: R0*R1 = R0 add R1 times (LOOP) // D <- R1. R1 is used for loop count. @R1 D=M // if R1 <= 0 then got END (loop END) @END D;JLE // R2 += R0. R1 times. @R0 D=M @R2 M=D+M // R1-- for loop count @R1 M=M-1 @LOOP 0;JMP (END) @END 0;JMP