我有一项作业,要求我使用递归计算x ^ n。提供了功能power的C源代码,我必须将其翻译为汇编语言,但是我是汇编的新手,有点卡住了,所以不确定该怎么做。
到目前为止,这是我的代码:
AREA powerXn, CODE, READONLY
ENTRY
MOV r0, #2 ;Value of x.
MOV r1, #3 ;Value of n.
ADR sp, stack ;Points sp to start of stack.
BL main
loop B loop
main STMFD sp!, {r0, r1, r2, r3, lr} ;Pushes registers on to stack.
BL power
LDMFD sp!, {r0, r1, r2, r3, pc} ;Pops values from stack.
power STMFD sp!, {r0, r1, lr} ;Pushes registers on to stack.
CMP r1, #0 ;Checks the base case
MOVEQ r2, #1 ;Sets r2 to be 1 if base case is reached
BNE test ;If base case not reached, jump to test.
MUL r3, r0, r2
LDMFD sp!, {r0, r1, pc}
test TST r1, #1 ;Checks if r1 (n) is odd
BNE odd ;If it is odd, jump to odd
BEQ even ;Otherwise jump to even
odd SUB r1, r1, #1 ;Subtract 1 from r1 (n).
BL power ;Recurse back to power.
MUL r3, r0, r2
LDMFD sp!, {r0, r1, pc}
even ;Not sure what to do here and not sure if what i have done so far is right.
AREA powerXn, DATA, READWRITE
ALIGN
space 0x200
stack DCD 0x00
END
我需要翻译的C语言源代码是:
int power(int x, unsigned int n){
int y;
if (n == 0)
return 1;
if (n & 1) // if n is odd
return x * power(x, n - 1);
else { // if n is even
y = power(x, n >> 1); // n >> 1 means n/2
return y * y;
}
}
答案 0 :(得分:1)
您似乎对C更加熟悉,所以我建议转到https://godbolt.org/并尝试使用C到汇编器功能。您所要做的就是选择一个正确的编译器(ARM GCC有一些选项)并浏览汇编代码。当然,我强烈反对简单地复制代码而不先尝试理解它,但是该网站应该至少为您提供有关操作的线索。我目前正在与FASM学习x86汇编程序,该网站是我进行研究期间的首选之地。