8

In intel instruction, idiv(integer divsion) means signed division.
I got the result of idiv, but I don't quite understand the result.

- Example

0xffff0000 idiv 0xffff1100


- My wrong prediction
As long as I know, quotient should be 0, and remainder should be 0xffff0000 and because...

0xffff0000 / 0xffff1100 = 0  
0xffff0000 % 0xffff1100 = 0xffff0000  


- However, the result was...
Before idiv

eax            0xffff0000            # dividend
esi            0xffff1100            # divisor
edx            0x0                     

After idiv

eax            0xfffeedcc            # quotient
edx            0x7400   29696        # remainder


- Question.
The result was value I couldn't expected.
Could someone explain about signed division(idiv)?


- Appended. Here's More information about idiv.
idiv uses the eax register as a source register.
As a result of execution, quotient is stored at eax, and remainder is stored at edx.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Jiwon
  • 1,074
  • 1
  • 11
  • 27
  • You say "8086 instruction" but then you use "eax" and "edx" which are not 8086 registers. Please clarify. Note also that the idiv instruction uses the (e)dx register as a source register, which you did not specify. – Raymond Chen Jan 02 '19 at 03:57
  • @RaymondChen Thank you for your advice. I edited my question to be more clear. – Jiwon Jan 02 '19 at 04:05
  • @Jiwon - the question still doesn't show what is in edx before idiv. – rcgldr Jan 02 '19 at 04:06
  • 1
    Have you looked at something like [(idiv) IA-32 Assembly Language Reference Manual](https://docs.oracle.com/cd/E19455-01/806-3773/instructionset-44/)? – David C. Rankin Jan 02 '19 at 04:18
  • Possible duplicate of [IDIV in assembly isn't giving me the wanted result (NASM)](https://stackoverflow.com/questions/37552056/idiv-in-assembly-isnt-giving-me-the-wanted-result-nasm) – Raymond Chen Jan 02 '19 at 15:34

1 Answers1

9

idiv divides edx:eax by the explicit source operand. See Intel's instruction manual entry.

Since edx is 0, edx:eax is a positive number. You are dividing 4294901760 by -61184, giving -70196 with a remainder of 29696.

Remember that both dividend (EDX:EAX) and divisor (ESI in your case) are interpreted as 2's complement signed numbers, so any bit-pattern with the high bit set is negative.

00000000ffff0000 = 4294901760
ffff1100 = -61184
fffeedcc = -70196
7400 = 29696

You should sign extend eax into edx using cdq before using idiv, instead of zero-extending by zeroing EDX.

However, that still won't give the results you were expecting, because -65536 divided by -61184 equals 1 with a remainder of -4352.


(A negative dividend and positive divisor would give a negative remainder: X86 IDIV sign of remainder depends on sign of dividend for 8/-3 and -8/3?)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
prl
  • 11,716
  • 2
  • 13
  • 31