发布时间:2024-05-07 14:01
程序需求:编程写一个名为Gcd的求两个数最大公约数子程序,主子程序间的参数传递通过堆栈完成。调用Gcd子程序求出三个双自变量:dvar1、dvar2与dvar3的最大公约数并输出。
编程思路:先写出C实现,再转换为汇编实现。为了降低难度,子程序中不单独开辟栈空间来存储变量,直接通过EBP对传入参数进行访问。
Win10 + VS2017
#include
int dvar1 = 12;
int dvar2 = 6;
int dvar3 = 18;
int gcd(int a, int b)
{
int tmp = b;
while (a%b != 0)
{
tmp = a % b;
a = b;
b = tmp;
}
return tmp;
}
int main()
{
int res = gcd(dvar1, gcd(dvar2, dvar3));
printf("the result is : %d\n", res);
return 0;
}
INCLUDELIB kernel32.lib
INCLUDELIB ucrt.lib
INCLUDELIB legacy_stdio_definitions.lib
.386
.model flat,stdcall
ExitProcess PROTO,
dwExitCode:DWORD
printf PROTO C : dword,:vararg
scanf PROTO C : dword,:vararg
.data
dvar1 dword 12
dvar2 dword 6
dvar3 dword 18
msg byte 'the result is : %d',10,0
.code
main Proc
push dword ptr dvar3
push dword ptr dvar2
call gcd
push eax
push dword ptr dvar1
call gcd
invoke printf,offset msg,eax
push 0h
call ExitProcess
main endp
gcd proc
push ebp
mov ebp,esp
push ebx
push ecx
push edx
mov ecx,dword ptr [ebp+12]
jmp testing
body:
mov eax,dword ptr [ebp+8]
mov ebx,dword ptr [ebp+12]
cdq
div ebx
mov ecx,edx
mov dword ptr [ebp+8],ebx
mov dword ptr [ebp+12],ecx
testing:
mov eax,dword ptr [ebp+8]
mov ebx,dword ptr [ebp+12]
cdq
div ebx
cmp edx,0
jne body
mov eax,ecx
pop edx
pop ecx
pop ebx
pop ebp
ret 8
gcd endp
end main