In: Computer Science
Use MARS to write and simulate a MIPS assembly language program to implement the strlen function. The program should ask for a user's input and print the length of the user's input. Write the main function to call strlen.
The main function should:
- Prompt the user for input
- Pass that input to strlen using registers $a0.
- Preserve (i.e. push onto the stack) any T registers that the main
function uses. The strlen function should:
- Preserve any S registers it uses.
- Determine the length of the string.
- Return the length of the string to main using register $v0.
Code:
.data
# reserve 100 bytes for user input
inputString: .space 100
.text
.globl main
main:
# load the address of the space where string is to be stored
la $a0, inputString
# load how many characters to read
li $a1, 100
# syscall code to read a string
li $v0, 8
syscall
# load address of the string for passing to strlen function
la $a0, inputString
# call strlen function
jal strlen
# load the value returned by strlen from $v0 to $a0 for printing
add $a0, $zero, $v0
# syscall code to print an integer
li $v0, 1
syscall
# syscall code to exit the program
li $v0, 10
syscall
# strlen function takes string in $a0, returns it's length in $v0
strlen:
# initialize our counter $t0 to -1, so that null character is not counted
li $t0, -1
# loop through the string
loop:
# load the byte at address $a0 to $t1
lb $t1, 0($a0)
# if $t1 is '\0' i.e null character return
beqz $t1, return
# else increment the address in $a0 by 1
addi $a0, $a0, 1
# increment the counter by 1
addi $t0, $t0, 1
# loop again
j loop
# return the value of $t0 and exit the function
return:
# load the value to $t0 to $v0
add $v0, $zero, $t0
# return back to the main
jr $ra
OUTPUT: