# print a string in reverse, one-char-at-a-time, using a loop
#
# code uses registers a0, a7, t0, t1, t2
#
# Note: string contains only ASCII characters. UTF-8 has many more
# multi-byte characters.
.data
string: .asciz "Wow, does it work?"
.text
main:
# ---------- step 1. set string address and string char (byte) index
la t0, string # address of the first char (byte) of a string
li t1, 0 # initialize string char index
# ---------- step 2. loop looking for the end-of-the-string (null char)
locate_end_of_string:
# step 2.1 load string's (ASCII) char into a0
add t2, t1, t0 # set t2 to address of string char (t0 + t1)
lbu a0, 0(t2) # load char (byte) unsigned
# step 2.2 end of string? (a0 == null char)
beq a0, zero, found_end_of_string # If string char is null, exit the loop
# step 2.3 increment string char (byte) index
# jump to locate-end-of-string loop
addi t1, t1, 1 # increment string char index
j locate_end_of_string # loop
found_end_of_string:
addi t1, t1, -1 # decrement string char index
# to last char in string
# ---------- step 3. print string in reverse
start_print_loop:
# step 3.1 end of string? (a0 == 0) (a0 == null char)
blt t1, zero, end_print_loop # if string char index < zero,
# stop printing
# step 3.2 load string's (ASCII) char into a0
add t2, t1, t0 # set t2 to address of string char
# (t0 + t1)
lbu a0, 0(t2) # load char (byte) unsigned
# step 3.3 print string char
li a7, 11 # service code 11 = Print character
ecall
# step 3.4 decrement string char (byte) index
# jump to beginning of print loop
addi t1, t1, -1 # decrement string char index
j start_print_loop # loop
end_print_loop:
# ---------- step 4. exit program
li a0, 0 # returned value
li a7, 93 # exit program
ecall # Trigger exit system call