Is there a MulDiv equivalent for Linux?
The MulDiv function in the Windows API is equivalent (a*b)/c
, but stores the intermediate result a*b
into a 64-bit variable before dividing it by c
, to avoid integer overflow where a*b
greater than MAX_INT
but (a*b)/c
not.
WINBASEAPI
int
WINAPI
MulDiv(
_In_ int nNumber,
_In_ int nNumerator,
_In_ int nDenominator
);
When programming in Linux, is there an equivalent convenience function?
+3
source to share
1 answer
There seems to be no equivalent function for Linux.
I created a simple built in function that works (I haven't tested it with 64 bit compilation yet)
inline int mul_div(int number, int numerator, int denominator) {
long long ret = number;
ret *= numerator;
ret /= denominator;
return (int) ret;
}
+2
source to share