I’m new with assembler and trying to get how it works, i’ve got task to write a DotProduct function that calculates the scalar product of two
vectors of signed 16-bit integers (of the short int type). Vectors can be set as static
or dynamic arrays of the same length. The result of the function is a 32-bit
signed integer (type long). The function has the following header:
int DotProduct(short a[], short b[], int n)
The pairwise product of array elements is performed using the imul command,
then the 32-bit products are added in a loop that runs through all the elements
of the arrays. If at some point the addition operation led to a signed overflow,
you need to interrupt the calculation cycle and output 0x80000000 (i.e. -2^31) as a result.
Before exiting
the function, the result of calculations is placed in the eax register, and thus the value
of the function will be returned to the calling program. In the case of n=0, the function should
return 0.
I’ve done code, but it works a bit incorrect, when i’m trying to check signed overflow situation i get 65536=2^16 instead of -2^31,and also vec2 couldn’t work correct with ‘-‘ sign.
#include <iostream>
#include <limits.h>
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:
movsx edx, word ptr[esi];
imul dx, word ptr[edi];
jo overflow_check;
add eax, edx;
add esi, 2;
add edi, 2;
sub ecx, 1;
jnz loop_start;
jmp end;
overflow_check:
mov[result], -2147483648;
jmp exit;
end:
mov[result], eax;
exit:
}
return result;
}
int main() {
short int vec1[] = { -5, -1 };
short int vec2[] = { 1, 1 };
int l = 2;
long result = DotProduct(vec1, vec2, l);
std::cout << "Dot product: " << result << std::endl;
return 0;
}
Sheesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.