gpt4 book ai didi

c - ARMv7汇编语言: How to reverse a char array and output it to another char array

转载 作者:行者123 更新时间:2023-11-30 16:19:41 30 4
gpt4 key购买 nike

我是一个正在研究 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

最佳答案

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

现在,

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

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

R2,在上面的strlen_loop中,遍历了strIn,此时包含了其结束地址。现在,R0 也包含该地址,其余代码与 strOut 无关。它尝试反转 strIn

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

关于c - ARMv7汇编语言: How to reverse a char array and output it to another char array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554093/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com