12.13.1 Multiply "32-bit int * 32-bit int = 64-bit long long int"

Multiply "32-bit int * 32-bit int = 64-bit long long int"

To multiply 32 bits by 32 bits to obtain a 64-bit result, cast the 32-bit integer to a 64-bit integer (long long) and then perform the multiplication operation as follows.

Example:

  long long test (int a, int b)
  {
    return (long long) a * b;
    // Same as (long long) a * (long long) b
    // NOT the same as (long long) (a * b)
  }

We can then access the highest 32-bit result from HI as follows.

Example:

  typedef union
  {
    long long a;   // One 64-bit accumulator
    int b[2];      // 32-bit HI and LO
  } a64_union;
  int test (int a, int b)
  {
    a64_union temp;
    temp.a = (long long) a * b;
    return temp.b[1];  // Access the HI 32 bits
  } 
  # Illustrative generated assembly with optimizations
  test:
    mult    $4,$5
    mfhi    $2
    j       $31