Sign in to follow this  

x86 assembly Q, IDIV problem

This topic is 2640 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

I am trying to write a simple compiler in F#.
The first thing I am doing is parsing maths expressions such as
(1+2)*3

Everything is working fine, it will consume very long complex maths operations with
+,-,*,/,(,) and integers.

One issue I have encountered is the divide fails when the dividend is negative e.g.

1/-1 ->
MOV EBX, 1
PUSH EBX
MOV EBX, -1
POP EAX
XOR EDX, EDX
IDIV EBX
PUSH EAX

-1/1 ->
MOV EBX, -1
PUSH EBX
MOV EBX, 1
POP EAX
XOR EDX, EDX
IDIV EBX
PUSH EAX

the second 1 throws an exception.

I am assembling with MASM32 on a Pentium Core2 Duo x64 running Windows XP Prof 32bit.

Why does this fail? I cant find any source which explains why, are you not allowed negative dividends?
The only other way I can deal with this is to swap the signs when appropriate (or negate the result) but that feels like a dirty hack and will mess up my lovely recursive stateless function :(

Thank You

Share this post


Link to post
Share on other sites
You need to sign-extend the dividend (typically by replacing XOR EDX,EDX with CDQ.) Otherwise IDIV tries to divide 0xFFFFFFFF in EDX:EAX by one and you get an overflow exception since the resulting quotient won't fit in a signed 32-bit integer.

Share this post


Link to post
Share on other sites

This topic is 2640 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this