Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to MulDiv for Linux?

Tags:

c++

linux

winapi

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?

like image 608
sashoalm Avatar asked Feb 14 '13 10:02

sashoalm


1 Answers

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;
}
like image 166
sashoalm Avatar answered Oct 17 '22 23:10

sashoalm