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.
Code
// 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: 2The 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
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.