ARMv7汇编语言:如何反转一个char数组并将其输出到另一个char数组

时间:2019-04-06 22:41:49

标签: c assembly arm arm7

我是对ARM7汇编语言编程的初学者。

我正在尝试在ARM程序集中实现一个简单的函数,该函数接受一个char数组,将其反转,然后将其存储到另一个相等长度的char数组中。

我在下面同时包括了我的C代码和ARM7汇编语言代码。但是,我的代码没有输出正确的反向字符串。这可能是由于我的ASM说明造成的。我在32位计算机上运行Linux。

reverseString.s(下面的代码)

.global reverseString

.text

reverseString:
    MOV R2, R1          @store strIn[0] into R2
    PUSH {R4-R6}        @save regs
    MOV R4, #0          @R4 will be strIn_len reg, store 0 for count

@finds the length of the strIn arr
strlen_loop:
    LDR R3, [R2], #1    @increment through strIn arr
    ADD R4, R4, #1      @count the no. of chars
    CMP R3, #0          @check if null term hit
    BNE strlen_loop     @if yes leave, else cont.

@string reversal loop
    MOV R0, R2          @movs ptr of strOut to last element
loop:
    CMP R4, #0          @makes sure count !=0
    BEQ loop_end        @if yes, end loop
    LDR R5, [R1], #1    @incr. address of strIn in R1 and put into R5
    STR R5, [R0], #-1   @store the value at address in strOut
    SUB R4, R4, #1      @decrement counter var
    B loop

loop_end:
    POP {R4-R6} @restore regs
    BX LR

reverseString.c(下面的代码)

#include <stdio.h>
#include <stdint.h>

extern void reverseString(char strOut[], const char strIn[]);

#define COUNT 6

int main()
{ 
  const char strIn[COUNT] = "candy";
  char strOut[COUNT];
  reverseString(strOut, strIn);
  printf("%s\r\n", strOut);
  return 0;
}

使用命令行编译

gcc -g -o reverseString reverseString.s reverseString.c
./reverseString

output

1 个答案:

答案 0 :(得分:0)

尝试一个实验。将strOut初始化为某个内容,并在调用reverseString之后打印strInstrOut。观察一些有趣的输出。

现在,在

        MOV R0, R2          @movs ptr of strOut to last element

最后一个元素到底是什么?

上面R2中的

strlen_loop遍历了strIn,此时包含其结尾的地址。现在R0还包含该地址,其余代码与strOut没有任何关系。它会尝试反转strIn

此举不仅有害,而且多余。只需从[R2], #-1复制到[R0], #1