News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

How do you guys handle overflow with division?

Started by cork, August 13, 2010, 02:31:30 AM

Previous topic - Next topic

cork

One thing I don't like about the DIV instruction is that if the quotient does not fit into the quotient register, an arithmetic overflow interrupt occurs.

I would prefer it to set a flag instead and let me test for the overflow, just as one would with the ADC or SBB instructions.

Looking at the DIV instruction for 16-bit value divided by an 8-bit value, I have to ensure that the numerator is less than divisor*256, or else an arithmetic overflow interrupt could occur.

While I can do this easily with a SHL and CMP, but it seems a real pain in the ass to have to calculate the limit for every division that I perform.

Is there some way to "handle" an arithmetic overflow with the program? Can you specify an address within your procedure, for it to jump to when this happens? Or will it always crash your program?

cork

To recap, the other threads explained:
  For 64-bits divided by 32-bit, where 64-bits is in EDX:EAX, just make sure that divisor > EDX.

Which kills two birds with one stone, as it tests for division by zero as well. That's pretty nifty - I probably wouldn't have thought of that.

I'm happy - I learned something new tonight!

dedndave

you can cascade DIV instructions together to handle larger dividends
where you are limited is the size of the divisor and remainder (the max size of the remainder is divisor-1)
for those operations, long division or floating point is required
i think if you search the forum for the term "cascade" or "multiple precision divide", you should find some examples
to handle very large integers, a loop may be used to cascade several DIV operations
i might add - the DIV instruction isn't the fastest thing going
if you are dividing by a constant, you can use qWord's magic number program and use MUL instructions instead