The Math.imul() function returns the result of the C-like 32-bit multiplication of the two parameters.
Syntax
Math.imul(a, b)
Parameters
a- First number.
b- Second number.
Return value
The result of the C-like 32-bit multiplication of the given arguments.
Description
Math.imul() allows for fast 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).
Examples
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
Polyfill
This can be emulated with the following function:
Math.imul = Math.imul || function(a, b) {
var ah = (a >>> 16) & 0xffff;
var al = a & 0xffff;
var bh = (b >>> 16) & 0xffff;
var bl = 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 ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
};
Specifications
| 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. |
Draft |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Feature | Chrome | Firefox | Edge | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic Support | 28 | 20 | (Yes) | (No) | 16 | 7 |
| Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
|---|---|---|---|---|---|---|---|
| Basic Support | (Yes) | (Yes) | (Yes) | 20 | (No) | (Yes) | 7 |
Document Tags and Contributors
Tags:
Contributors to this page:
fscholz,
jameshkramer,
rwaldron,
Peppesterest,
anton-bannykh,
eduardoboucas,
Mingun,
realityking,
kirilloid,
kscarfone,
ethertank,
evilpie,
Sheppy,
ziyunfei,
mkato,
jvilk,
berkerpeksag,
jrmuizel,
teoli
Last updated by:
fscholz,