Integer modulo can be implemented in two ways:
First, using a DIV or IDIV where the remainder will be placed in EDX , but first you need to specify zero EDX or quote intel:
Operand Size ----------- | Dividends | Division | Quotes | The remainder
Square / double word | EDX: EAX | r / m32 | EAX | Edx.
eg:
eax = eax % 9
when unsigned becomes:
XOR EDX,EDX ;clear the destinations for outputs. this stops the garbage remainder MOV ECX,9 DIV ECX MOV EAX,EDX
when it is signed, it is:
MOV ECX,9 CDQ ;this will clear EDX due to the sign extension IDIV ECX MOV EAX,EDX
The second method is the optimization used when you use two modulo, in this case you are AND one less than the two, for example: eax = eax % 8 becomes AND EAX,7 .
source share