A clever homebrew modulus implementation

前端 未结 5 1815
甜味超标
甜味超标 2021-02-06 04:29

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

5条回答
  •  逝去的感伤
    2021-02-06 04:41

    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;
    }
    

提交回复
热议问题