【アセンブリ】whileループの繰り返し処理を作る【MIPS】
某Patterson&Hennesy本を参考にしながらCで以下のように実現できるwhileループをアセンブリ言語で作ってみる
while (i > k) { printf("Hello") i += 1; }
書いてく
まずは前準備。前回やったsyscallの順序に従って...。
.data .align 2 str: .asciiz "Hello" .text main: li $v0, 4 # for syscall of print_string la $a0, str # $a0 = address (of "Hello") li $s0, 0 # initialize i li $s1, 2 # number of loop
$s0はloop.cでいうiのかわり、$s1はkのかわり。kの値を変えれば繰り返す回数を変えれる。
Loopラベルを、戻ってくる地点として設定して、Exitラベルまでをwhileループの中みたいな感じにする。
Loop: bgt $s0, $s1, Exit # go to Exit if $s0 > $s5 syscall addi $s0, $s0, 1 # i = i + 1 ($s0=$s0+1) j Loop # go to Loop Exit: j $ra
ソースコード
以下のようになった。
.data .align 2 str: .asciiz "Hello" .text main: li $v0, 4 # for syscall of print_string la $a0, str # $a0 = address (of "Hello") li $s0, 0 # initialize i li $s1, 2 # number of loop Loop: bgt $s0, $s1, Exit # go to Exit if $s0 > $s5 syscall addi $s0, $s0, 1 # i = i + 1 ($s0=$s0+1) j Loop # go to Loop Exit: j $ra
だんだんアセンブリ言語の独特な感覚にもやっと慣れてきたかもしれない。
いちいち命令を調べたりするのめんどくさい。プログラミング言語って、最初がまじで何やってるかわからなすぎて難しいんだよな...。
早くそこを突破できるよういろいろやってみよう。