I\'m programming a PLC with some legacy software (RSLogix 500, don\'t ask) and it does not natively support a modulus operation, but I need one. I do not have access to: modulus
This is a loop based on the answer by @Keith Randall, but it also maintains the result of the division by substraction. I kept the printf's for clarity.
#include
#include
#define NBIT (CHAR_BIT * sizeof (unsigned int))
unsigned modulo(unsigned dividend, unsigned divisor)
{
unsigned quotient, bit;
printf("%u / %u:", dividend, divisor);
for (bit = NBIT, quotient=0; bit-- && dividend >= divisor; ) {
if (dividend < (1ul << bit) * divisor) continue;
dividend -= (1ul << bit) * divisor;
quotient += (1ul << bit);
}
printf("%u, %u\n", quotient, dividend);
return dividend; // the remainder *is* the modulo
}
int main(void)
{
modulo( 13,5);
modulo( 33,11);
return 0;
}