imul Multiplies In 32 Bit Wraparound

Math.imul performs real 32-bit integer multiplication with wrap-around, where plain * continues in double precision and silently loses low bits.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
// Math.imul multiplies in true 32-bit space and wraps; plain * keeps
// going in double precision, so the two diverge past 2^53
const a = 0xdeadbeef;
const b = 0x41c6ce6e;

console.log('plain multiply:', a * b);
console.log('Math.imul     :', Math.imul(a, b));
console.log('as unsigned hex:', (Math.imul(a, b) >>> 0).toString(16));

// Both agree while the product still fits in double precision
console.log('small inputs:', Math.imul(3, 4), 3 * 4);

// Operands are truncated to 32-bit integers before multiplying
console.log('truncates operands:', Math.imul(1.9, 2.9));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

plain multiply: 4122776541730331600
Math.imul     : -635020110
as unsigned hex: da265cb2
small inputs: 12 12
truncates operands: 2

The execution narrative

The demo output is labeled (plain multiply:, as unsigned hex:, small inputs:), so every printed line maps back to its originating operation.

Output is labeled for readability — expect lines prefixed with plain multiply:, as unsigned hex:, small inputs:.

Key statements

const a = 0xdeadbeef;
const b = 0x41c6ce6e;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed.