我有一个关于 x86 汇编中 64 位乘法的实现的问题。我已经发布了我能够理解的代码。我不知道其余的人在做什么(而且我可能在我已经做过的事情中犯了错误)。任何方向将不胜感激。
dest at %ebp+8
x at %ebp+12
y at %ebp+16
movl 16(%ebp), %esi //Move y into %esi
movl 12(%ebp), %eax //Move x into %eax
movl %eax, %edx //Move x into %edx
sarl $31, %edx //Shift x right 31 bits (only sign bit remains)
movl 20(%ebp), %ecx //Move the low order bits of y into %ecx
imull %eax, %ecx //Multiply the contents of %ecx (low order bits of y) by x
movl %edx, %ebx //Copy sign bit of x to ebx
imull %esi, %ebx //Multiply sign bit of x in ebx by high order bits of y
addl %ebx, %ecx //Add the signed upper order bits of y to the lower order bits (What happens when this overflows?)
mull %esi //Multiply the contents of eax (x) by y
leal (%ecx,%edx), %edx
movl 8(%ebp), %ecx
movl %eax, (%ecx)
movl %edx, 4(%ecx)
下面是64位乘法的算法:
x, y: 64-bit integer
x_h/x_l: higher/lower 32 bits of x
y_h/y_l: higher/lower 32 bits of y
x*y = ((x_h*2^32 + x_l)*(y_h*2^32 + y_l)) mod 2^64
= (x_h*y_h*2^64 + x_l*y_l + x_h*y_l*2^32 + x_l*y_h*2^32) mod 2^64
= x_l*y_l + (x_h*y_l + x_l*y_h)*2^32
Now from the equation you can see that only 3(not 4) multiplication needed.
movl 16(%ebp), %esi ; get y_l
movl 12(%ebp), %eax ; get x_l
movl %eax, %edx
sarl $31, %edx ; get x_h, (x >>a 31), higher 32 bits of sign-extension of x
movl 20(%ebp), %ecx ; get y_h
imull %eax, %ecx ; compute s: x_l*y_h
movl %edx, %ebx
imull %esi, %ebx ; compute t: x_h*y_l
addl %ebx, %ecx ; compute s + t
mull %esi ; compute u: x_l*y_l
leal (%ecx,%edx), %edx ; u_h += (s + t), result is u
movl 8(%ebp), %ecx
movl %eax, (%ecx)
movl %edx, 4(%ecx)
你也可以检查这个在32位机器上实现64位算术 https://stackoverflow.com/questions/11680720/implement-64-bit-arithmetic-on-a-32-bit-machine?rq=1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)