Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.
# --------- Implementation of strcat() in MIPS ---------- #
# call strcat() twice:
# 1. append var_source1 to var_target
# 2. append var_source2 to the result above
# 3. print the end result
# ------------------------------------------------------- #
.data
var_target:  .ascii  "My name is "
             .space  20
var_source1: .asciiz "Antonis "
var_source2: .asciiz "Kyprianou"
var_message: .asciiz "The final concatenated string is: " 
# ------------------------------------------------------- #
.text
# ------ load source and target string addresses -------- #
    la $a1, var_target
    la $a0, var_source1
    jal strcat                    # call strcat() function
# ------ load source and target string addresses -------- #
    la $a1, var_target
    la $a0, var_source2
    jal strcat                    # call strcat() function
# ------------------------ print message ---------------- #
    la $a0, var_message           # address of string to be
                                  # printed
    li $v0, 4                     # print string
    syscall
# ----------------- print concatenated string ----------- #
    la $a0, var_target            # address of string to be
                                  # printed
    li $v0, 4                     # print string
    syscall
# --------------------- exit program -------------------- #
    li $v0,10
    syscall
# ---------------------- strcat() ----------------------- #
strcat:                           # loop until end of
                                  # target found
    lb $t1, 0($a1)
    beq $t1, $zero, append        # is this a '\0' ?
    addi $a1, $a1, 1
    j strcat
append:
    lb $t1, 0($a0)                # read char from source
    sb $t1, 0($a1)                # append the char to the
                                  # target
    addi $a0, $a0, 1
    addi $a1, $a1, 1
    bne $t1, $zero, append        # is this a '\0' ?
return:
    jr $ra                        # yes, it is a '\0',
                                  # return to the caller
# ------------------------------------------------------- #
Please let me know of any suggestions or bugs regarding the code above.
Regards,
Antonis
 
No comments:
Post a Comment