Imported Upstream version 2.9.0
[debian/cc1111] / device / lib / pic16 / libsdcc / long / modulong.c
1 /*-------------------------------------------------------------------------
2    _modulong.c - routine for modulus of 32 bit unsigned long
3
4              Written By -  Sandeep Dutta . sandeep.dutta@usa.net (1999)
5
6              Bug fixes by Martijn van Balen, aed@iae.nl
7
8    This library is free software; you can redistribute it and/or modify it
9    under the terms of the GNU Library General Public License as published by the
10    Free Software Foundation; either version 2, or (at your option) any
11    later version.
12
13    This library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU Library General Public License for more details.
17
18    You should have received a copy of the GNU Library General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
22    In other words, you are welcome to use, share and improve this program.
23    You are forbidden to forbid anyone else to use, share and improve
24    what you give them.   Help stamp out software-hoarding!
25 -------------------------------------------------------------------------*/
26
27 #include <sdcc-lib.h>
28
29 #define MSB_SET(x) ((x >> (8*sizeof(x)-1)) & 1)
30
31 unsigned long _modulong (unsigned long a, unsigned long b) _IL_REENTRANT
32 {
33   unsigned char count = 0;
34
35   while (!MSB_SET(b))
36   {
37      b <<= 1;
38      if (b > a)
39      {
40         b >>=1;
41         break;
42      }
43      count++;
44   }
45   do
46   {
47     if (a >= b)
48       a -= b;
49     b >>= 1;
50   }
51   while (count--);
52
53   return a;
54 }