Skip to content

Instantly share code, notes, and snippets.

@tombasche
Created December 5, 2020 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombasche/c2e98cbafb89703b0966b044ba893f77 to your computer and use it in GitHub Desktop.
Save tombasche/c2e98cbafb89703b0966b044ba893f77 to your computer and use it in GitHub Desktop.
Reverse string in mips
# Mips program to reverse a string
# mips.s
.data
str: .space 128 # character buffer
.text
.globl main
main: # input the string
li $v0, 8 # service code
la $a0, str # address of buffer
li $a1, 128 # buffer length
syscall
li $t0, 0 # push a null
subu $sp, $sp, 4 # onto the stack
sw $t0, ($sp) # to signal its bottom
li $t1, 0 # index of first char in str
pushl: # push each character on the stack
lbu $t0, str($t1) # get current char into a full word
beqz $t0, stend # null byte: end of string
subu $sp, $sp, 4 # push the full word
sw $t0, ($sp) # holding the char
addu $t1, $t1 1 # increment the index
j pushl # loop
stend: # pop chars from stack back into the buffer
li $t1, 0 # index of first byte of str
popl:
lw $t0, ($sp) # pop a char off the stack
addu $sp, $sp, 4
beqz $t0, done # null means empty stack
sb $t0, str($t1) # store at string[$t1]
addu $t1, $t1, 1 # increment the index
j popl
done: # print the reversed string
li $v0, 4 # service code
la $a1, str # address of string
syscall
li $v0, 10 # exit
syscall
#end of program
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment