NASM:将大数字划分为小数字

时间:2011-05-11 06:40:09

标签: assembly 64-bit nasm division

NASM手册在DIV上说:

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

如果EDX:EAX是2 59 附近的大数且分隔符是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

1 个答案:

答案 0 :(得分:2)

此代码未经测试。它应该计算(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