如何在程序集中实现mod运算符

Son*_*ell 6 x86 assembly

我正在学习汇编语言的分工.根据我正在学习的书,idiv操作的结果放在eax中,其余部分放在edx中.

书中的练习是number = result % divisor在装配中实施.

我原以为这相当于正常的除法运算,除了edx就是结果.

然而这并没有起作用,而edx似乎又回来了垃圾.

为什么?你如何在汇编中实现上面的伪代码?

Nec*_*lis 17

整数模数可以通过两种方式实现:

首先使用DIV或者IDIV,其余的将被放入EDX,但你需要先归零EDX,或引用英特尔:

Operand Size -----------| Dividend | Divisor | Quotient | Remainder
Quadword/doubleword     | EDX:EAX  |  r/m32  |   EAX    |   EDX. 
Run Code Online (Sandbox Code Playgroud)

例如:

eax = eax % 9
Run Code Online (Sandbox Code Playgroud)

当无符号成为:

XOR EDX,EDX ;clear the destinations for outputs. this stops the garbage remainder  
MOV ECX,9
DIV ECX
MOV EAX,EDX
Run Code Online (Sandbox Code Playgroud)

签名时,它是:

MOV ECX,9
CDQ ;this will clear EDX due to the sign extension
IDIV ECX
MOV EAX,EDX
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用2的幂模数时使用的优​​化,在这种情况下,你AND比2的幂小1,例如:eax = eax % 8变为AND EAX,7.

  • @Necrolis这对签名号码不起作用.我得到负面结果.哪个不对. (2认同)