mulDiv#

Fully qualified name: carb::math::mulDiv

Defined in carb/math/MulDiv.h

inline cpp::optional<uint64_t> carb::math::mulDiv(
uint64_t num,
uint64_t multiplier,
uint64_t divisor,
) noexcept#

Multiplies two 64-bit unsigned integers and then divides the 128-bit result by a third 64-bit unsigned 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:

uint128_t temp = uint128_t(num) * multiplier;
if (!divisor || (temp >> 64) >= divisor)
    return cpp::nullopt; // overflow or divide by zero
return uint64_t(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.

Note

This function rounds toward zero, the default for integer math. If a different rounding mode is desired, pass a rounding policy as the first parameter.

Parameters:
  • 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.