I am trying to divide two numbers 50 and 5. This is my code:
function Divide(Num1, Num2: Integer): Integer;
asm
MOV EAX, Num1
CDQ
MOV ECX, Num2
IDIV ECX
MOV @RESULT, ECX
end;
It gives me a DivisionByZeroException
exception in Delphi.
Can someone tell me what am I doing wrong ?
It's the CDQ
instruction. From an online reference:
Converts signed DWORD in EAX to a signed quad word in EDX:EAX by extending the high order bit of EAX throughout EDX
The problem is, Num2
being the second parameter, is stored in EDX, and since you're running CDQ
before loading EDX to ECX, what ends up in ECX is 0. Rewrite it like this, and your routine works as expected:
function Divide(Num1, Num2: integer): integer;
asm
MOV EAX, Num1
MOV ECX, Num2
CDQ
IDIV ECX
MOV @Result, EAX
end;