# reverse.spim --- Read, reverse, and echo a line from the console. # Demonstrates syscalls for reading and writing strings, as well the use # of lb/sb to access characters within a string. .data line: .space 80 prompt: .asciiz "Enter a line to be echoed.\n" nl: .asciiz "\n" .text .globl main main: # Print the prompt. li $v0, 4 # Syscall code for print string. la $a0, prompt # Starting address of string. syscall # Read the input. li $v0, 8 # Syscall code for read string. la $a0, line # Starting address of buffer. li $a1, 80 # Length of buffer. syscall # Print a newline. li $v0, 4 la $a0, nl syscall # Now, let's reverse the string. la $s0, line # $s0 points to beginning of line. la $s1, line # So does $s1, for now. # We want $s1 pointing to the '\n' at the # end of the line. while1: lb $t0, 0($s1) beq $t0, 10, ewhile1 addi $s1, $s1, 1 b while1 ewhile1: addi $s1, $s1, -1 # Now, $s1 points to the last character # of the line. # Ok, $s0 points to the beginning of the # line and $s1 points to the end. Start # swapping characters to reverse the string. while2: bge $s0, $s1, ewhile2 lb $t0, 0($s0) lb $t1, 0($s1) sb $t0, 0($s1) sb $t1, 0($s0) addi $s0, $s0, 1 addi $s1, $s1, -1 b while2 ewhile2: li $v0, 4 # Print the reversed string. la $a0, line syscall # Return to SPIM. li $v0, 10 # Syscall code for exit. syscall