Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Efficient integer arithmetic

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?

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.

like image 301
Michael Williamson Avatar asked Apr 18 '11 20:04

Michael Williamson


People also ask

Does JavaScript have an integer type?

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

How do you divide numbers in JavaScript?

Division (/)The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

How do you subtract numbers in JavaScript?

The subtraction operator ( - ) subtracts the two operands, producing their difference.

What are special numbers in JavaScript?

JavaScript has several special number values: Two error values, NaN and Infinity . Two values for zero, +0 and -0 . JavaScript has two zeros, a positive zero and a negative zero, because the sign and the magnitude of a number are stored separately.


1 Answers

So, what's the most efficient way to implement integers in JavaScript?

The primitive number type is as efficient as it gets. Many modern JS engines support JIT compilation, so it should be almost as efficient as native floating-point arithmetic.

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.

You can achieve the semantics of standard 32-bit integer arithmetic by noting that JavaScript converts "numbers" to 32-bit integers for bitwise operations. >>> (unsigned right shift) converts its operand to an unsigned 32-bit integer while the rest (all other shifts and bitwise AND/OR) convert their operand to a signed 32-bit integer. For example:

  • 0xFFFFFFFF | 0 yields -1 (signed cast)
  • (0xFFFFFFFF + 1) | 0 yields 0 (overflow)
  • -1 >>> 0 yields 0xFFFFFFFF (unsigned cast)
like image 172
casablanca Avatar answered Sep 30 '22 20:09

casablanca