67cff5846ee7d6c7f6c68432c6c8feee69eedf8a
[reactos.git] / reactos / lib / kernel32 / misc / muldiv.c
1 /* $Id: muldiv.c,v 1.1 2002/12/06 13:14:14 robd Exp $
2 *
3 */
4 #include <windows.h>
5
6
7 /***********************************************************************
8 * MulDiv (KERNEL32.@)
9 * RETURNS
10 * Result of multiplication and division
11 * -1: Overflow occurred or Divisor was 0
12 */
13
14 //FIXME! move to correct file
15 INT STDCALL MulDiv(
16 INT nMultiplicand,
17 INT nMultiplier,
18 INT nDivisor)
19 {
20 #if SIZEOF_LONG_LONG >= 8
21 long long ret;
22
23 if (!nDivisor) return -1;
24
25 /* We want to deal with a positive divisor to simplify the logic. */
26 if (nDivisor < 0)
27 {
28 nMultiplicand = - nMultiplicand;
29 nDivisor = -nDivisor;
30 }
31
32 /* If the result is positive, we "add" to round. else, we subtract to round. */
33 if ( ( (nMultiplicand < 0) && (nMultiplier < 0) ) ||
34 ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
35 ret = (((long long)nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
36 else
37 ret = (((long long)nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
38
39 if ((ret > 2147483647) || (ret < -2147483647)) return -1;
40 return ret;
41 #else
42 if (!nDivisor) return -1;
43
44 /* We want to deal with a positive divisor to simplify the logic. */
45 if (nDivisor < 0)
46 {
47 nMultiplicand = - nMultiplicand;
48 nDivisor = -nDivisor;
49 }
50
51 /* If the result is positive, we "add" to round. else, we subtract to round. */
52 if ( ( (nMultiplicand < 0) && (nMultiplier < 0) ) ||
53 ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
54 return ((nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
55
56 return ((nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
57
58 #endif
59 }
60
61