不使用64位整数将两个32位数字相乘

问题描述:

我们正在使用以下算法进行32bit * 32bit乘法

We are doing some 32bit * 32bit multiplication using the following algorithm

让我们我们想将a(32位)与b(32位)都乘以有符号,

Let us we want to multiply a (32 bit) with b (32 bit), both signed,

a = ah * 2 ^ 16 + al [ah-高16位,al-低16位]

a = ah * 2^16 + al [ah - Higher 16 bits, al - Lower 16 bits]

b = bh * 2 ^ 16 + bl [bh-高16位,bl-低16位]

b = bh * 2^16 + bl [bh - Higher 16 bits, bl - Lower 16 bits]

我们正在有效地

结果=(al * bl)+(((ah * bl)+(al * bh))* 2 ^ 16)+((ah * bh)* 2 ^ 32)~~~

Result = (al * bl) + (((ah * bl) + (al * bh)) * 2^16) + ((ah * bh) * 2 ^ 32) ~~~

我的问题

他们有更好的方法吗?

在任何主流编译器中,在32位平台上仿真64位int的效率将与自己进行多步数学的效率差不多.但这将更加可靠.

In any mainstream compiler, the emulation of 64-bit ints on a 32-bit platform will be about as efficient as doing the mutli-step math yourself. But it will be much more reliably correct.

当使用值大到足以溢出的简单算术时,即使是我见过的最优化的数学库,也只使用int64.

When doing simple arithmetic with values large enough to overflow, even the most highly tuned math library that I've seen just uses int64.