我有一个任务,要求我使用递归计算x ^ n。提供了功能强大的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;
}
}
你似乎对C更熟悉,所以我建议去https://godbolt.org/并尝试他们的C-to-assembler功能。您所要做的就是选择正确的编译器(ARM GCC有选项)并查看汇编代码。当然,我强烈不同意简单复制代码而不首先理解代码,但该网站应该至少给你一个关于该做什么的线索。我目前正在学习使用FASM的x86汇编程序,这个网站是我研究期间的首选。