mulDiv#

Fully qualified name: carb::math::mulDiv

Defined in carb/math/MulDiv.h

template<class RoundPolicy>
cpp::optional<int64_t> carb::math::mulDiv(
RoundPolicy round,
int64_t num,
int64_t multiplier,
int64_t divisor,
) noexcept#

Multiplies two 64-bit signed integers and then divides the 128-bit result by a third 64-bit signed integer.

Typically multiplying num * multiplier can result in overflowing a 64-bit value. This function uses a 128-bit temporary value for the multiplication operation, and then divides it by a 64-bit value. Effectively performs:

int128_t temp = int128_t(num) * multiplier;
if (!divisor || (abs(temp) >> 64) >= abs(divisor))
    return cpp::nullopt; // overflow or divide by zero
return int64_t(round(temp / divisor));

If the result will not fit in a 64-bit value, or divisor is zero, carb::cpp::nullopt is returned to indicate the math error.

Parameters:
  • round – The rounding policy to use. See round_toward_zero, round_away_from_zero and round_nearest_neighbor.

  • num – The multiplicand.

  • multiplier – The multiplier, multiplied with num produces a 128-bit value.

  • divisor – The divisor, used to divide the 128-bit product of num X multiplier.

Returns:

A carb::cpp::optional containing the 64-bit result of the operation. If divisor is zero, or the result would not fit in a 64-bit value, carb::cpp::nullopt is returned instead.