xref: /OK3568_Linux_fs/u-boot/lib/ldiv.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun /* Copyright (C) 1992, 1997 Free Software Foundation, Inc.
2*4882a593Smuzhiyun    This file is part of the GNU C Library.
3*4882a593Smuzhiyun 
4*4882a593Smuzhiyun  * SPDX-License-Identifier:	LGPL-2.0+
5*4882a593Smuzhiyun  */
6*4882a593Smuzhiyun 
7*4882a593Smuzhiyun typedef struct {
8*4882a593Smuzhiyun 	long    quot;
9*4882a593Smuzhiyun 	long    rem;
10*4882a593Smuzhiyun } ldiv_t;
11*4882a593Smuzhiyun /* Return the `ldiv_t' representation of NUMER over DENOM.  */
12*4882a593Smuzhiyun ldiv_t
ldiv(long int numer,long int denom)13*4882a593Smuzhiyun ldiv (long int numer, long int denom)
14*4882a593Smuzhiyun {
15*4882a593Smuzhiyun   ldiv_t result;
16*4882a593Smuzhiyun 
17*4882a593Smuzhiyun   result.quot = numer / denom;
18*4882a593Smuzhiyun   result.rem = numer % denom;
19*4882a593Smuzhiyun 
20*4882a593Smuzhiyun   /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
21*4882a593Smuzhiyun      NUMER / DENOM is to be computed in infinite precision.  In
22*4882a593Smuzhiyun      other words, we should always truncate the quotient towards
23*4882a593Smuzhiyun      zero, never -infinity.  Machine division and remainer may
24*4882a593Smuzhiyun      work either way when one or both of NUMER or DENOM is
25*4882a593Smuzhiyun      negative.  If only one is negative and QUOT has been
26*4882a593Smuzhiyun      truncated towards -infinity, REM will have the same sign as
27*4882a593Smuzhiyun      DENOM and the opposite sign of NUMER; if both are negative
28*4882a593Smuzhiyun      and QUOT has been truncated towards -infinity, REM will be
29*4882a593Smuzhiyun      positive (will have the opposite sign of NUMER).  These are
30*4882a593Smuzhiyun      considered `wrong'.  If both are NUM and DENOM are positive,
31*4882a593Smuzhiyun      RESULT will always be positive.  This all boils down to: if
32*4882a593Smuzhiyun      NUMER >= 0, but REM < 0, we got the wrong answer.  In that
33*4882a593Smuzhiyun      case, to get the right answer, add 1 to QUOT and subtract
34*4882a593Smuzhiyun      DENOM from REM.  */
35*4882a593Smuzhiyun 
36*4882a593Smuzhiyun   if (numer >= 0 && result.rem < 0)
37*4882a593Smuzhiyun     {
38*4882a593Smuzhiyun       ++result.quot;
39*4882a593Smuzhiyun       result.rem -= denom;
40*4882a593Smuzhiyun     }
41*4882a593Smuzhiyun 
42*4882a593Smuzhiyun   return result;
43*4882a593Smuzhiyun }
44