【问题标题】:NASM: Dividing large number with small oneNASM:除以大数
【发布时间】:2011-08-23 01:06:57
【问题描述】:

NASM 手册上说 DIV:

  • 对于 DIV r/m32,EDX:EAX 除以给定的操作数;商存储在 EAX 中,余数存储在 EDX 中。

如果EDX:EAX 是一个大约 259 的大数并且分隔符是 3 怎么办?商显然不能适应EAX。假设我不关心其余部分。我想要一个进行除法的最佳实践。

考虑在不同的步骤中划分高位和低位 32 位。我想我可以找出一些丑陋的结果,但我会对一个好的结果感兴趣。快速检查EAX 可能持有商的情况,从而避免复杂的魔法。

解决方案:drhirsch 的答案转换为 NASM 语法:

; this divides edx:eax by ebx, even if the result is bigger than 2^32.
; result is in edx:eax, ecx,esi are used as spare registers
mov ecx, eax           ;save lower 32 bit
mov eax, edx
xor edx, edx           ;now edx:eax contains 0:hi32 
div ebx
mov esi, eax           ;hi 32 bit of result, save to esi
mov eax, ecx           ;now edx:eax contains r:lo32, where r is the remainder
div ebx
mov edx, esi           ;restore hi32

【问题讨论】:

    标签: assembly 64-bit nasm division


    【解决方案1】:

    此代码未经测试。它应该计算 (d*2^32 + a)/b:

    ;this divides edx:eax by ebx, even if the result is bigger than 2^32.
    ;result is in edx:eax, ecx,esi are used as spare registers
    ;AT&T syntax.
      mov %eax, %ecx           ;save lower 32 bit
      mov %edx, %eax
      xor %edx, %edx           ;now edx:eax contains 0:hi32 
      div %ebx
      mov %eax, %esi           ;hi 32 bit of result
      mov %ecx, %eax           ;now edx:eax contains r:lo32, where r is the remainder
      div %ebx
      mov %esi, %edx           ;restore hi32                 
    

    【讨论】:

    • 最后一行是mov %esi, %edx吗?
    • 是的,已修复。我很少能在不引入错误的情况下编写 10 行代码 :-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2018-04-21
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2013-03-14
    相关资源
    最近更新 更多