我刚刚开始学习汇编,我很难理解如何将一个数组复制到另一个数组。
例如,假设我有两个数组J和K:
J和K都包含5个元素,它们都是8位宽的数字。
J = [0, 1, 2, 3, 4]
K = [5, 6, 7, 8, 9]
J位于寄存器1,K位于寄存器2
我该如何"追加"/"复制"呢?J到K?(如果这是正确的思考方式的话)
会是:
LDR R3, R1[0] ; placing 0th J element into register R3
MOV R2, R3 ; Moving the R3 element into the array K
....
....
....
继续,直到所有元素都被复制到数组K
因此,我试图获得的结果是一个数组,其中包含两个初始数组的元素result =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
我确信这是完全错误的,所以如果有人能够为我阐明这一点,我将非常感激!
这当然可以在汇编中完成,但由于以下几个原因,这很困难:
- 您需要知道数组的位置,并确保在尝试复制它们时不会覆盖任何重要的内容。比方说,你想把K直接拷贝到J后面。如果其他重要的东西存储在J后面,那么它就会被擦除!
- 每个数组有多大?这对你和我来说都是显而易见的,但计算机并没有真正的线索。你有两个选择:自己测量或者提前知道数组的大小。
- 对于每种数据类型,你需要一个不同的例程。
对于这个示例代码,我将假设您希望将附加的数组J+K放在内存的单独部分中,该部分不会覆盖您正在使用的任何内容。同样,这段代码假设两个数组的大小都是5字节。这并不是特别有用,因为你可能希望你的代码能够处理各种大小的数组,而不仅仅是这一个特定的大小。
LDR R2,=ARRAY_J
LDR R3,=ARRAY_K
LDR R4,=ARRAY_L
MOV R1,#5 @ size of ARRAY_J goes here.
loop_append_J:
LDRB R0,[R2],#1 @ load R0 from ARRAY_J, add 1 to the pointer so we read the
@ next byte on the next pass.
STRB R0,[R4],#1 @ store R0 into ARRAY_L (ARRAY J + ARRAY K), add 1 to the
@ pointer
SUBS R1,R1,#1 @ decrease loop counter and set the flags accordingly
BNE loop_append_J @ if R1 doesn't equal zero, loop again.
MOV R1,#5 @ size of ARRAY_K goes here
loop_append_K:
LDRB R0,[R3],#1 @ this is pretty much the same story, just with the second
@ array. R4 already points to where it needs to.
STRB R0,[R4],#1
SUBS R1,R1,#1
BNE loop_append_K
@ now your program is done, do whatever you need to do to return, be it BX LR or whatever
.data @ forgive me if the syntax is wrong, I'm used to VASM which doesn't
@ have data directives like this.
ARRAY_J:
.byte 0,1,2,3,4 @whatever directive you use to define 8-bit values
ARRAY_K:
.byte 5,6,7,8,9 @whatever directive you use to define 8-bit values
ARRAY_L: @empty space to hold the new array.
.space 64,0 @this is more than enough room to store the new array.