Is There an Equivalent to Muldiv for Linux?

The MulDiv convenience function in Windows API is equivalent to (a*b)/c, but it stores the intermediate result of a*b in a 64-bit variable before dividing it by c to avoid integer overflow where a*b is greater than MAX_INT but (a*b)/c is not.

WINBASEAPI
int
WINAPI
MulDiv(
    _In_ int nNumber,
    _In_ int nNumerator,
    _In_ int nDenominator
    );

When programming in Linux, is there an equivalent convenience function?

4

1 Answer

It seems there is no equivalent function for Linux.

I created a simple inline function that works (I haven't tested it with 64-bit compilation though)

inline int mul_div(int number, int numerator, int denominator) {
    long long ret = number;
    ret *= numerator;
    ret /= denominator;
    return (int) ret;
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest