如何在 JavaScript 中实现 Big Int?

发布于 2025-01-12 08:33:35 字数 149 浏览 3 评论 0原文

我正在从事开源项目。由于 JavaScript 数字的表示形式,即 let、const...,它不能正确满足其规范。我想添加对 Int、Long Int 和 Big Ints 的支持,类似于 C++。

任何人都可以建议任何资源或方法来实现这一目标吗?

谢谢

I am working on open-source project. It doesn’t properly meet its specs due to the representation as JavaScript numbers ie let,const... I want to add support for Int, Long Int, and Big Ints similar to c++.

Can anyone please suggest any resource or approach to achieve this?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳若烟 2025-01-19 08:33:35

JavaScript 已获得 BigInt 支持作为一项功能几年前。到目前为止,大多数用户都拥有足够新的浏览器来支持它:https://caniuse.com/bigint

如果您想支持更旧的浏览器,有多种具有不同优缺点的纯 JavaScript 实现,例如 JSBI , MikeMcl 的 bignumber.js, Peter Olson 的 BigInteger.jsYaffle 的 BigInteger。您可以研究它们的来源以了解它们是如何实现的。

要了解如何实现本机 BigInt,这篇 V8 博客文章提供了一些见解。

旁注:JavaScript 完全能够像 C++ int/int32_t 一样表达 32 位整数,不需要 BigInt 或库。按位二进制运算使 JavaScript 数字的行为类似于 32 位整数,因此您可以编写 (a + b) | 0 使加法的行为类似于 C++ int 加法。

如果您需要的只是 64 位整数,那么将它们表示为 32 位数字对并不困难。还有几个现有的库可以做到这一点(只需使用您最喜欢的搜索引擎)。如果您实际上不需要任意大的整数,那么这可能是一个不错的选择。

JavaScript has gained BigInt support as a feature a couple of years ago. By now, most users have browsers new enough to support it: https://caniuse.com/bigint.

If you want to support even older browsers, there are a variety of pure JavaScript implementations with different pros and cons, for example JSBI, MikeMcl's bignumber.js, Peter Olson's BigInteger.js, Yaffle's BigInteger. You can study their sources to learn how they're implemented.

For learning about how native BigInt is implemented, this V8 blog post gives some insight.

Side note: JavaScript is perfectly capable of expressing 32-bit integers à la C++ int/int32_t, no BigInts or libraries are required for that. Bitwise binary operations cause JavaScript numbers to behave like 32-bit integers, so you can write (a + b) | 0 to make the addition behave like a C++ int addition.

If all you need is 64-bit integers, it's not difficult to represent them as pairs of 32-bit numbers. There are also several existing libraries that do that (just use your favorite search engine). If you don't actually need arbitrarily big integers, that may be a nice alternative.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文