Skip to content

Instantly share code, notes, and snippets.

@benwrk
Last active February 22, 2018 17:52
Show Gist options
  • Save benwrk/9af41da1a196bfd8bdb457818aa50ae2 to your computer and use it in GitHub Desktop.
Save benwrk/9af41da1a196bfd8bdb457818aa50ae2 to your computer and use it in GitHub Desktop.
Manual compilation of C to MIPS R3000 Assembly - Shifts the first element of an array to position 9 (0-indexed)
#
# Manual compilation - C to MIPS R3000 Assembly
#
# Shift the first element of an array to position 9 (0-indexed)
#
# Author: Benjapol Worakan (benwrk)
#
.data
array: .word 0 : 20 # int A[20] // array declaration
size: .word 10 # int size = 10 // actual size
i: .word 0 # int i = 0 // loop runner
.text
.globl main
main:
la $t0, array # int[] A
lw $t1, size # int size
loop:
lw $t2, i # // loads i
bge $t2, 9, exit # while (i < 9) // "bge" = will jump to "exit" if i >= 9
mul $t3, $t2, 4 # // multiply array offset/index by 4 (32-bit integer = 4 words)
add $t4, $t0, $t3 # // add array offset/index to the base address
lw $t5, 0($t4) # tmp = A[i]
lw $t6, 4($t4) # tmp2 = A[i + 1]
sw $t6, 0($t4) # A[i] = tmp2
sw $t5, 4($t4) # A[i + 1] = tmp
addi $t2, $t2, 1 # i = i + 1
sw $t2, i # // stores back i
#
j loop # continue
exit:
li $v0, 10 # // 10 = exit syscall code
syscall # return
int A[20];
int i = 0;
while (i < 9) {
int tmp = A[i];
A[i] = A[i + 1];
A[i + 1] = tmp;
i = i + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment