Nossos voluntários ainda não traduziram este artigo para o Português (do Brasil). Junte-se a nós e ajude-nos a fazer o trabalho!
Você também pode ler o artigo em English (US).

The Math.imul() function returns the result of the C-like 32-bit multiplication of the two parameters.


var product = Math.imul(a, b);


First number.
Second number.

Return value

The result of the C-like 32-bit multiplication of the given arguments.


Math.imul() allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten. Because imul() is a static method of Math, you always use it as Math.imul(), rather than as a method of a Math object you created (Math is not a constructor). If you use normal JavaScript floating point numbers in imul, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. The reason imul exists is because it is faster in only one (so far) circumstance: AsmJS. AsmJS allows for JIST-optimizers to more easily implement internal integers in JavaScript. Multiplying two numbers stored internally as integers (which is only possible with AsmJS) with imul is the only potential circumstance where Math.imul may prove performant in current browsers.


Using Math.imul()

Math.imul(2, 4);          // 8
Math.imul(-1, 8);         // -8
Math.imul(-2, -2);        // 4
Math.imul(0xffffffff, 5); // -5
Math.imul(0xfffffffe, 5); // -10


This can be emulated with the following function:

Math.imul = Math.imul || function(a, b) {
  var aHi = (a >>> 16) & 0xffff;
  var aLo = a & 0xffff;
  var bHi = (b >>> 16) & 0xffff;
  var bLo = b & 0xffff;
  // the shift by 0 fixes the sign on the high part
  // the final |0 converts the unsigned value into a signed value
  return ((aLo * bLo) + (((aHi * bLo + aLo * bHi) << 16) >>> 0) | 0);


Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Math.imul' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Math.imul' in that specification.

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support28 Yes20 No167
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support Yes Yes Yes20 Yes7 Yes

Etiquetas do documento e colaboradores

Última atualização por: wbamberg,