Thursday, February 20, 2020

Reverse values in an array by using the stack

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.

# Example to reverse values in an array by using the stack     #
# ------------------------------------------------------------ #

# -------------------- Data Declarations --------------------- #
.data
array: .word  1,  3,  5,  7,  9, 11, 13, 15, 17, 19
       .word 21, 23, 25, 27, 29, 31, 33, 35, 37, 39
       .word 41, 43, 45, 47, 49, 51, 53, 55, 57, 59

length: .word 30

# ------------------- Text/Code section ---------------------- #

# Basic approach:
# - loop to push each element onto the stack
# - loop to pop each element off the stack
# Final result is all elements reversed

.text

main:
# ------------------------------------------------------------ #
    # Loop to read items from array and push to stack.
    la $t0, array                 # array starting address
    li $t1, 0                     # loop index, i=0
    lw $t2, length                # length
# ------------------------------------------------------------ #

PushLoop:
    lw $t4, ($t0)                 # get array[i]
    addiu $sp, $sp, -4            # push array[i]
    sw $t4, ($sp)
    
    addi $t1, $t1, 1              # i = i+1
    addi $t0, $t0, 4              # update array address
    
    blt $t1, $t2, PushLoop        # if i<length -> continue
# ------------------------------------------------------------ #
    # Loop to pop items from stack and write into array.
    la $t0, array                 # array starting address
    li $t1, 0                     # loop index, i=0
    
    lw $t2, length                # length (redundant line)
# ------------------------------------------------------------ #

PopLoop:
    lw $t4, ($sp)
    addiu $sp, $sp, 4             # pop array[i]
    sw $t4, ($t0)                 # set array[i]
    
    addi $t1, $t1, 1              # i = i+1
    addi $t0, $t0, 4              # update array address
    
    blt $t1, $t2, PopLoop         # if i<length, continue
# ------------------------------------------------------------ #
    # Done, terminate program.
    li $v0, 10                    # terminate
    syscall                       # system call

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment