Is it possible to calculate result of multiplication without using instructions MUL, IMUL, SHL, SHR, LOOP, JMP in x86 assembly language?
Is it possible to calculate result of multiplication without using instructions MUL, IMUL, SHL, SHR, LOOP, JMP in x86 assembly language?
Yes.
Without MUL the normal approach is "SHIFT LEFT and TEST and ADD" in a loop, like this:
result = 0;
while(a > 0) {
result = result << 1;
if( a & 0x80000000 != 0) {
result = result + b;
}
a = a << 1;
}
Note that a loop like this for 32-bit integers will have (at most) 32 iterations.
You can replace these shifts with additions (e.g. shl eax, 1
replaced with add eax, eax
); and you can replace LOOP
with an explicit loop (e.g. dec ecx
, jne next
) or unroll the loop (repeat the code 32 times). These replacements will probably improve performance.
Once you have unsigned multiplication, IMUL
can be replaced with branches that convert the values to positive and uses unsigned multiplication. E.g. like:
if(a < 0) {
a = -a;
if(b < 0) {
b = -b
return a*b; // Unsigned multiplication
} else {
return -a*b; // Unsigned multiplication
}
} else {
if(b < 0) {
b = -b
return -a*b; // Unsigned multiplication
} else {
return a*b; // Unsigned multiplication
}
}