The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: The Rogue on July 19, 2008, 02:48:48 AM

Title: Dividing
Post by: The Rogue on July 19, 2008, 02:48:48 AM
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.

Title: Re: Dividing
Post by: jdoe on July 19, 2008, 03:06:05 AM

Unsigned division

8 / 2 = 4

Result in EAX = 4


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


Title: Re: Dividing
Post by: sinsi on July 19, 2008, 03:07:25 AM
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).
Title: Re: Dividing
Post by: dsouza123 on July 19, 2008, 03:08:30 PM
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.
Title: Re: Dividing
Post by: Crackers on July 31, 2008, 04:48:35 PM
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
Title: Re: Dividing
Post by: dsouza123 on August 01, 2008, 03:03:02 AM
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.
Title: Re: Dividing
Post by: Crackers on August 01, 2008, 09:46:49 PM
Thanks, I'll try that.
Title: Re: Dividing
Post by: silentenigma on September 29, 2009, 06:35:13 AM
Thanks that was what i was searching for. I didnt use the ecx register so i couldnt get the result :cheekygreen: