cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

_modulong.c (1797B)


      1/*-------------------------------------------------------------------------
      2   _modulong.c - routine for modulus of 32 bit unsigned long
      3
      4   Copyright (C) 1999, Sandeep Dutta . sandeep.dutta@usa.net
      5             Bug fixes by Martijn van Balen, aed@iae.nl
      6
      7   This library is free software; you can redistribute it and/or modify it
      8   under the terms of the GNU General Public License as published by the
      9   Free Software Foundation; either version 2, or (at your option) any
     10   later version.
     11
     12   This library is distributed in the hope that it will be useful,
     13   but WITHOUT ANY WARRANTY; without even the implied warranty of
     14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15   GNU General Public License for more details.
     16
     17   You should have received a copy of the GNU General Public License
     18   along with this library; see the file COPYING. If not, write to the
     19   Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
     20   MA 02110-1301, USA.
     21
     22   As a special exception, if you link this library with other files,
     23   some of which are compiled with SDCC, to produce an executable,
     24   this library does not by itself cause the resulting executable to
     25   be covered by the GNU General Public License. This exception does
     26   not however invalidate any other reasons why the executable file
     27   might be covered by the GNU General Public License.
     28-------------------------------------------------------------------------*/
     29
     30#define MSB_SET(x) ((x >> (8*sizeof(x)-1)) & 1)
     31
     32unsigned long _modulong (unsigned long a, unsigned long b)
     33{
     34  unsigned char count = 0;
     35
     36  while (!MSB_SET(b))
     37  {
     38     b <<= 1;
     39     if (b > a)
     40     {
     41        b >>=1;
     42        break;
     43     }
     44     count++;
     45  }
     46  do
     47  {
     48    if (a >= b)
     49      a -= b;
     50    b >>= 1;
     51  }
     52  while (count--);
     53
     54  return a;
     55}