我是汇编器新手。无法在以太网中找到解决方案,所以在这里询问。这段代码输出了错误的数字,我不明白为什么。
#include <iostream>
long DotProduct(short int* vec1, short int* vec2, int l)
{
long result;
_asm
{
mov esi, [vec1];
mov edi, [vec2];
mov ecx, [l];
xor eax, eax;
loop_start:
movzx edx, word ptr[esi];
imul edx, word ptr[edi];
add eax, edx;
add esi, 2;
add edi, 2;
sub ecx, 1;
jnz loop_start;
}
return result;
}
int main() {
short int vec1[] = { 1, 2, 3 };
short int vec2[] = { 5, 6, 7 };
int l = 3;
long result = DotProduct(vec1, vec2, l);
std::cout << "Dot product: " << result << std::endl;
}
您需要将值从
short int
更改为 int
,并将汇编器中的增量调整为 esi
和 edi
为 4
。您还需要将最终数字从 eax
移至 result
变量中。
所以代码应该是:
#include <iostream>
long DotProduct(int* vec1, int* vec2, int l)
{
long result;
_asm
{
mov esi, [vec1];
mov edi, [vec2];
mov ecx, [l];
xor eax, eax;
loop_start:
movzx edx, word ptr[esi];
imul edx, word ptr[edi];
add eax, edx;
add esi, 4;
add edi, 4;
sub ecx, 1;
jnz loop_start;
mov[result], eax
}
return result;
}
int main() {
int vec1[] = { 1, 2, 3 };
int vec2[] = { 5, 6, 7 };
int l = 3;
long result = DotProduct(vec1, vec2, l);
std::cout << "Dot product: " << result << std::endl;
}