Math.imul()
is a JavaScript method that performs a 32-bit integer multiplication, returning the result as a signed 32-bit integer.
It is used when you need precise integer multiplication without floating-point inaccuracies, especially in scenarios where exact 32-bit integer arithmetic is needed, such as certain algorithms or performance-critical applications.
Key Characteristics of Math.imul()
- 32-bit Integer Multiplication: Unlike the standard multiplication operator (
*
), which can produce floating-point results,Math.imul()
ensures that the result is confined to 32-bit integer arithmetic. - Bitwise Operations: It handles overflow by wrapping around, similar to how C or C++ would handle 32-bit integers.
Syntax
Math.imul(a, b)
a
: The first operand (integer).b
: The second operand (integer).
Examples
// Basic multiplication
console.log(Math.imul(2, 3)); // 6
// Overflow example
console.log(Math.imul(0x80000000, 0x80000000)); // 0
// Negative numbers
console.log(Math.imul(-2, 3)); // -6
// Large numbers
console.log(Math.imul(0x7fffffff, 2)); // -2 (overflow wraps around)
// Multiplying zero
console.log(Math.imul(0, 10)); // 0
// Multiplying one
console.log(Math.imul(1, 10)); // 10
// Combining positive and negative numbers
console.log(Math.imul(5, -4)); // -20
// Multiplying positive and zero
console.log(Math.imul(5, 0)); // 0
// Multiplying negative and zero
console.log(Math.imul(-5, 0)); // 0
// Multiplying two negative numbers
console.log(Math.imul(-5, -4)); // 20
Explanation of Examples
- Basic Multiplication:
Math.imul(2, 3)
computes 6. - Overflow Example: Multiplying large integers that exceed 32-bit capacity results in wrap-around, producing
0
. - Negative Numbers: Negative and positive multiplication results in a negative product.
- Large Numbers: Demonstrates overflow, where large numbers exceed 32-bit integer range.
- Zero Multiplication: Any number multiplied by zero results in zero.
- One Multiplication: Any number multiplied by one remains unchanged.
- Combining Signs: Positive times negative equals negative.
- Combining Zero and Positive: Zero times any positive number is zero.
- Combining Zero and Negative: Zero times any negative number is zero.
- Two Negative Numbers: Multiplying two negatives results in a positive number.
These examples illustrate the usage of Math.imul()
and how it behaves with various types of inputs, including handling overflow and ensuring 32-bit integer arithmetic.
Tags:
JavaScript