Multiplication and Division in Assembly
C code:
| |
Dissassembled;
| |
DIV - Unsigned divide
Three forms:
- Unsigned divide ax by r/m8, al = quotient, ah = remainder
- Unsigned divide edx:eax by r/m32, eax = quotient, edx = remainder
- Unsigned divide rdx:rax by r/m64, rax = quotient, rdx = remainder
If dividend is 32/64 bits, edx/rdx will just be set to 0 by the compiler before the instruction.
If the divisor is 0, a divide by zero exception is raised!
Example 1
Initial state:
+-----+-----------+
| ax | r/m8 (cx) |
+-----+-----------+
| 0x8 | 0x3 |
+-----+-----------+
Operation: div cx
After:
+-----+-----------+
| ah | al |
+-----+-----------+
| 0x2 | 0x2 |
+-----+-----------+
Example 2
Initial state:
+-----+-----+-----------+
| rdx | rax | r/m64(rcx)|
+-----+-----+-----------+
| 0x0 | 0x8 | 0x5 |
+-----+-----+-----------+
Operation: div rcx
After:
+-----+-----+-----------+
| rdx | rax | r/m64(rcx)|
+-----+-----+-----------+
| 0x3 | 0x1 | 0x5 |
+-----+-----+-----------+
IDIV - Signed divide
Three forms:
- Signed divide ax by r/m8, al = quotient, ah = remainder
- Signed divide edx:eax by r/m32, eax = quotient, edx = remainder
- Signed divide rdx:rax by r/m64, rax = quotient, rdx = remainder
If dividend is 32/64 bits, edx/rdx will just be set to 0 by the compiler before the instruction. If the divisor is 0, a divide by zero exception is raised!
Example 1
Initial state:
+------+-----------+
| ax | r/m8 (cx) |
+------+-----------+
| 0xFE | 0x2 |
+------+-----------+
Operation: idiv cx
After:
+-----+-----------+
| ah | al |
+-----+-----------+
| 0x0 | 0xFF |
+-----+-----------+
Example 2
Initial state:
+-----+----------+-----------+
| rdx | rax | r/m64(rcx)|
+-----+----------+-----------+
| 0x0 | 0x57e11a | 0xb01d |
+-----+----------+-----------+
Operation: idiv rcx
After:
+--------+-----+-----------+
| rdx | rax | r/m64(rcx)|
+--------+-----+-----------+
| 0x82B7 | 0x7F| 0xb01d |
+--------+-----+-----------+