在不使用 64 位 int 的情况下将两个 32 位数字相乘 [英] Multiplying two 32 bit numbers without using 64 bit int

查看:26
本文介绍了在不使用 64 位 int 的情况下将两个 32 位数字相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用以下算法进行一些 32 位 * 32 位乘法

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) ~~~

我的问题,

他们有没有更好的方法来做到这一点?

Is their any better way to do this?

推荐答案

在任何主流编译器中,在 32 位平台上模拟 64 位整数与自己进行多步数学计算一样有效.但它会更可靠地正确.

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.

这篇关于在不使用 64 位 int 的情况下将两个 32 位数字相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆