我知道自从有人问这个问题以来已经有一段时间了,但这可以帮助遇到类似问题的其他人。如果您不想以线性方式对此进行编码,这将有点棘手。
- 首先,我将设置循环以循环遍历每个数组项
- 存储您当前用于此循环的所有寄存器
- 创建第二个循环来处理乘法
- 存储值并退出第二个循环
- 恢复你的第一个循环的寄存器
- 增加循环计数器,然后跳回循环顶部
下面是一些示例代码,循环遍历数组中的每个元素并将它们相乘。将结果存储在数组 arr3 中后。
代码:
.ORIG x3000
MAIN
AND R1, R1, #0 ; LOOP counter
LOOP
LD R2, LIMIT
ADD R2, R2, R1 ; Check to see if we've hit our limit
BRz END_LOOP
LEA R2, arr1 ; Load the memory location of arr1
ADD R2, R2, R1 ; Add our array index to get our current arr1 memory location
LDR R3, R2, #0 ; Load the value at arr1[R1] into R3
LEA R2, arr2 ; Load the memory location of arr2
ADD R2, R2, R1 ; Add our array index to get our current arr2 memory location
LDR R4, R2, #0 ; Load the value at arr2[R1] into R4
; This loop is used to multiply our numbers
; R3 becomes our LOOP2 counter for the multiplication
; Example: 7 x 5 = 7 + 7 + 7 + 7 +7
;
AND R5, R5, #0
ADD R5, R5, R4 ; Make R5 = R4
ADD R3, R3, #-1 ; Reduce our count by 1
LOOP2
ADD R5, R5, R4 ; Add our second number to itself
ADD R3, R3, #-1 ; Decrease our loop counter
BRz END_L2 ; If our LOOP2 counter has reached 0 then break
BR LOOP2
END_L2
LEA R2, arr3 ; Load the memory location of arr3
ADD R2, R2, R1 ; Add our array index to get our current arr3 memory location
STR R5, R2, #0 ; Store our answer currently in R5 into the memory location stored in R2
ADD R1, R1, #1 ; Increment our loop counter
BR LOOP ; Branch to LOOP
END_LOOP
HALT
; Variables
LIMIT .FILL xFFFC ; Store the value of -4 into our loop limit variable
arr1 .FILL 5
.FILL 2
.FILL 7
.FILL 3
arr2 .FILL 7
.FILL 4
.FILL 1
.FILL 2
arr3 .BLKW 4 ; used to store our answer
.END