You neglected to explain why you zero EDX before you do the division, and to provide an example of signed division.
When the result for a quadword/doubleword division will not fit into EAX the processor generates an exception. For a quadword/doubleword unsigned division, zeroing EDX effectively limits the dividend to the 32-bit value in EAX, ensuring that the quotient will always fit into EAX, regardless of the divisor. It is possible to do quadword/doubleword unsigned divisions where the dividend is a full 64-bit value, without the processor generating an exception, provided that the value in EDX is less than the value of the divisor. For example, this code will not generate an exception, and will produce the correct result:
Code: Select all
asm
mov edx, 0xfffffffe
mov eax, 0xffffffff
mov ecx, 0xffffffff
div ecx
end asm
Note that for a quadword/doubleword signed division, zeroing EDX will not produce the correct result when the value in EAX is negative. To get the correct result, regardless of the sign of the divisor and dividend, you need to sign extend the EAX value into EDX, using the CDQ instruction provided for this purpose.
Code: Select all
'====================================================================
dim as integer n, d, q, r
'====================================================================
asm
mov eax, 2147483647
cdq '' extend sign bit of EAX into EDX
mov [r], edx
end asm
print bin(2147483647,32)
print bin(r,32)
asm
mov eax, -2147483648
cdq '' extend sign bit of EAX into EDX
mov [r], edx
end asm
print bin(-2147483648,32)
print bin(r,32)
print
'====================================================================
n = 123
d = 10
asm
mov ecx, [d]
mov eax, [n]
xor edx, edx
idiv ecx
mov [q], eax
mov [r], edx
end asm
print q, r
n = -123
d = 10
asm
mov ecx, [d]
mov eax, [n]
xor edx, edx
idiv ecx
mov [q], eax
mov [r], edx
end asm
print q, r
'====================================================================
n = 123
d = 10
asm
mov ecx, [d]
mov eax, [n]
cdq
idiv ecx
mov [q], eax
mov [r], edx
end asm
print q, r
n = -123
d = 10
asm
mov ecx, [d]
mov eax, [n]
cdq
idiv ecx
mov [q], eax
mov [r], edx
end asm
print q, r
sleep