How to implement mod statement in assembly

I am studying separation in assembler. According to the book I'm studying, the result of the idiv operation is placed in eax and the rest is in edx.

The exercise in the book is to implement number = result % divisor in the assembly.

I would think that this would be equivalent to a normal division operation, with the exception of edx.

However, this did not work, and edx returned the seemingly garbage.

Why? How did you implement the above pseudo code in the assembly?

+6
source share
1 answer

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 .

+15
source

Source: https://habr.com/ru/post/902145/


All Articles