使用要点
- 跑完文件,输出里会留下标记——
plain multiply:、as unsigned hex:、small inputs:。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。
核心语句
const a = 0xdeadbeef;
const b = 0x41c6ce6e;
代码示例
// 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));