JavaScript:高效的整数运算 [英] JavaScript: Efficient integer arithmetic
问题描述
我目前正在为编译为JavaScript的小语言编写编译器。在这种语言中,我非常喜欢使用整数,但JavaScript只支持Number,这是一个双精度浮点值。那么,在JavaScript中实现整数的最有效方法是什么?与仅使用Number相比,这有多高效?
I'm currently writing a compiler for a small language that compiles to JavaScript. In this language, I'd quite like to have integers, but JavaScript only supports Number, which is a double-precision floating point value. So, what's the most efficient way to implement integers in JavaScript? And how efficient is this compared to just using Number?
特别是,溢出行为应该与其他语言保持一致:例如,向INT_MAX添加一个应该给出INT_MIN。 。整数的值应为32位或64位
In particular, overflow behaviour should be consistent with other languages: for instance, adding one to INT_MAX should give INT_MIN. Integers should either be 32-bit or 64-bit.
推荐答案
我发现这个实施BigIntegers的在Javascript: http://www-cs-students.stanford.edu/~tjw/jsbn/
I found this implementation of BigIntegers in Javascript: http://www-cs-students.stanford.edu/~tjw/jsbn/
也许这会有所帮助?
编辑:此外,Google Closure库实现了64位整数:
的http:// code.google.com/p/closure-library/source/browse/trunk/closure/goog/math/long.js
Also, the Google Closure library implements 64-bit integers: http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/math/long.js
这些基本上只是虽然生成方便对象,但不会做任何改善基本数据类型效率的事情。
These are essentially just generating convenience objects though, and won't do anything for improving on the fundamental data-type efficiency.
这篇关于JavaScript:高效的整数运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!