assembly - 我如何获得负股息的正模

标签 assembly x86 integer-division

我正在尝试获取 [0 ... n-1] 范围内的模 n (0 < n)。

指令idiv n将 EDX:EAX(64 位)除以 n,然后离开
EAX=商,EDX=余数。 (n 是我代码中的寄存器)

我的问题是,当 EDX:EAX 的内容为负数时,我在 EDX 中得到负数结果。

我找到的最简单的解决方案是:

cdq            ; extend EAX sign bit to EDX
idiv n         ; edx = (possibly neg.) remainder
add edx, n
mov eax, edx   ; eax = remainder + n
cdq
idiv n         ; edx = positive remainder

是否有更清洁/更简单/更快捷的方法来获得正余数?

最佳答案

-5 mod 3 = -2(余数,-1 商)

修补余数:-2 + 3 = +1,这就是你想要的,对吧?

那么商是 -1 - 1 = -2。

验证:-2 * 3 + +1 = -5

cdq            ; extend EAX sign bit to EDX
idiv n         ; edx = (possibly neg.) remainder
mov eax, edx   ; eax = copy of remainder
add edx, n     ; negative remainder modified to positive one (for --quotient)
               ; when going from negative to positive, CF will be set (unsigned overflow)
cmovc eax,edx  ; when CF, load eax with modified remainder
; eax = to-be-positive-adjusted remainder

我没有在debugger里验证,只是醒了,所以先测试一下。

关于assembly - 我如何获得负股息的正模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40861023/

相关文章:

java - 整数除法 : How do you produce a double?

debugging - 即使 (--cx != 0),LOOP 指令也无法循环

汇编语言 - 不止一种类型?

rep_movsl 的 Clobber 列表

assembly - EMU8086 将 32 位数字除以 16 位数字给出意外的 0 余数

java - 可疑整数除法的检查样式规则?

prefetch - 为 ia32、ia64、amd64 和 powerpc 寻找预取指令的最佳等价物

c++ - 如何读取 Visual C++ 2010 生成的程序集输出?

x86 - x86 实模式下的段大小

x86 - 为什么编译器将数据放在PE和ELF文件的.text(code)部分中,并且CPU如何区分数据和代码?