News:

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

Dividing

Started by The Rogue, July 19, 2008, 02:48:48 AM

Previous topic - Next topic

The Rogue

For some reason, my programs are always crashing when i try to divide. I'm trying to divide two dwords. Would anyone be able to write just a quick snippet of dividing 2 random numbers, like 8 and 2 or something. It would be really appreciated.


jdoe


Unsigned division

8 / 2 = 4

Result in EAX = 4


    mov ecx, 2
    mov eax, 8
    xor edx, edx
    div ecx



sinsi

Using DWORDs means the 64-bit number in EDX:EAX is being divided by a 32-bit register (e.g. ECX), so make sure that EDX is zeroed (unsigned division) or sign extended (signed division).
Light travels faster than sound, that's why some people seem bright until you hear them.

dsouza123

division  64 bit (pair of 32 bit) / 32 bit -> 32 bit quotient (answer) EAX and 32 bit remainder EDX
The pair of source registers edx, eax (high and low dwords) are overwritten with the results of the division.


=== unsigned ===
mov edx, 0
mov eax, 8
mov ecx, 2
div ecx
mov quotient, eax
mov remainder, edx



=== signed ===
mov eax, 8
cdq             ; sign extend eax into edx
mov ecx, 2
idiv ecx
mov quotient, eax
mov remainder, edx


If the value of the 64 bit number is greater than 32 bits
then the divisor has to be bigger than the high 32 bits.

EDX:EAX  ECX  16:25  28 will work
EDX:EAX  ECX  16:25  8 will fail with an exception, because the result (quotient) doesn't fit in 32 bits.

Crackers

Hi, I have the same problem, I've already tried to extend the sign with cdq, but it now tells me that I have an "integer division by 0" exception(it used to be an integer overflow exception ). How can I track the error?
Thanks in advance

dsouza123

Before the division, check if the divisor is zero.
Put some debugging code before the division to trace how the divisor gets a zero value.
Or run it through a good assembly level debugger like ollydbg, stepping through the code.

Crackers

Thanks, I'll try that.

silentenigma

Thanks that was what i was searching for. I didnt use the ecx register so i couldnt get the result :cheekygreen:
My heart is ripped out,
Chained on my boots
Look deep inside mey soul with pain,
Witness the fall of a hero