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

编程入门 行业动态 更新时间:2024-10-25 12:28:43
本文介绍了有没有办法在 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 位整数相乘?

本文发布于:2023-11-30 01:37:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648287.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   整数   正确地   两个   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!