我正在尝试在 Assembly 中编写一个函数,该函数将返回数组中偶数元素的总和。这是我的代码
int sum(int *a, int n)
{
int S = 0;
_asm {
mov eax, [ebp + 8]
mov edx, 0
mov ebx, [ebp + 12]
mov ecx, 0
for1: cmp ecx, ebx
jge endfor
and [eax + ecx * 4], 1
jz even
inc ecx
jmp for1
even: add edx, [eax + ecx * 4]
inc ecx
jmp for1
endfor: mov S, edx
}
return S;
}
但这不起作用。有谁知道这是怎么回事以及我该如何解决它?谢谢。
只是一些猜测(特别是因为我不知道您使用的是什么编译器,并且您不清楚“不工作”的含义):
mov eax, [ebp + 8]
mov edx, 0
mov ebx, [ebp + 12]
mov ecx, 0
我认为这应该加载两个参数a
and n
到寄存器中。你怎么知道偏移量是正确的?是否可以直接引用名称?
and [eax + ecx * 4], 1
这会破坏输入数组中的元素(如果是奇数则将其设置为 1,如果是偶数则将其设置为 0),这可能是您不想要的。你可能应该使用test
指令(非破坏性)而不是and
.
even: add edx, [eax + ecx * 4]
这将添加 0,因为您已经设置了[eax + ecx * 4]
到 0 通过and
我上面提到的指令。基于此,我希望你的函数始终返回 0。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)