汇编代码,必须计算标量积

问题描述 投票:0回答:1

我是汇编器新手。无法在以太网中找到解决方案,所以在这里询问。这段代码输出了错误的数字,我不明白为什么。

#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;

}
c++ assembly inline-assembly
1个回答
0
投票

您需要将值从

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;

}
© www.soinside.com 2019 - 2024. All rights reserved.