Exponentiation function intel assembly
-
02-07-2021 - |
Question
Using bison to generate assembly code for a simple calculator, but I can't figure out exactly what my bug is here, all the answers seem to be one multiplication off...
global intpow
intpow:
push ebp
mov ebp,esp
mov ecx,[ebp+8]
mov eax,[ebp+12]
loop:
cmp eax,1
jle finish
dec eax
imul ecx,ecx
jmp loop
finish:
mov eax,ecx
mov esp,ebp
pop ebp
ret
Here's the code in my .y file when I identify an exponent call:
exp '^' exp { $$ = pow ($1, $3);
printf("call\tintpow\n");
printf("push\tDWORD eax\n");
}
Is the assembly wrong? The .y? Both?
Solution
(Comments converted to an Answer)
@DCoder wrote:
imul ecx, ecx
will overwrite the original value with the multiplied result. The second iteration of the loop will compute(y * y) * (y * y)
instead of(y * y) * y
, and so on.
@nrz wrote:
nstead of a power function you've written a tetration function, which is same as Knuth's double-arrow function. It's valid code, only for different purpose.
@hirschhornsalz wrote:
What you are calculating is x^(2^y).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow