有没有办法在 Javascript 中正确地将两个 32 位整数相乘? [英] Is there a way to correctly multiply two 32 bit integers in Javascript?

查看:16
本文介绍了有没有办法在 Javascript 中正确地将两个 32 位整数相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Javascript 中正确地将两个 32 位整数相乘?

Is there a way to correctly multiply two 32 bit integers in Javascript?

当我使用 long long 从 C 中尝试这个时,我得到了这个:

When I try this from C using long long I get this:

printf("0x%llx * %d = %llx
", 0x4d98ee96ULL, 1812433253,
      0x4d98ee96ULL * 1812433253);
==> 0x4d98ee96 * 1812433253 = 20becd7b431e672e

但是从 Javascript 中得到的结果是不同的:

But from Javascript the result is different:

x = 0x4d98ee97 * 1812433253;
print("0x4d98ee97 * 1812433253 = " + x.toString(16));
==> 0x4d98ee97 * 1812433253 = 20becd7baf25f000

尾随的零让我怀疑 Javascript 的整数分辨率在 32 位和 64 位之间奇怪地有限.

The trailing zeros lead me to suspect that Javascript has an oddly limited integer resolution somewhere between 32 and 64 bits.

有没有办法得到正确的答案?(我在 x86_64 Fedora 15 上使用 Mozilla js-1.8.5 以防万一.)

Is there a way to get a correct answer? (I'm using Mozilla js-1.8.5 on x86_64 Fedora 15 in case that matters.)

推荐答案

这似乎在没有外部依赖的情况下完成了我想要的:

This seems to do what I wanted without an external dependency:

function multiply_uint32(a, b) {
    var ah = (a >> 16) & 0xffff, al = a & 0xffff;
    var bh = (b >> 16) & 0xffff, bl = b & 0xffff;
    var high = ((ah * bl) + (al * bh)) & 0xffff;
    return ((high << 16)>>>0) + (al * bl);
}

这将执行 32 位乘法模 2^32,这是计算的正确下半部分.可以使用类似的函数来计算正确的上半部分并将其存储在一个单独的整数中(ah * bh 似乎是正确的),但我并不需要这样做.

This performs a 32-bit multiply modulo 2^32, which is the correct bottom half of the computation. A similar function could be used to calculate a correct top half and store it in a separate integer (ah * bh seems right), but I don't happen to need that.

注意零偏移.否则,只要设置了高位,该函数就会生成负值.

Note the zero-shift. Without that the function generates negative values whenever the high bit is set.

这篇关于有没有办法在 Javascript 中正确地将两个 32 位整数相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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