A clever homebrew modulus implementation

前端 未结 5 1812
甜味超标
甜味超标 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:53

    How many bits are you dealing with? You could do something like:

    if dividend > 32 * divisor  dividend -= 32 * divisor
    if dividend > 16 * divisor  dividend -= 16 * divisor
    if dividend > 8 * divisor  dividend -= 8 * divisor
    if dividend > 4 * divisor  dividend -= 4 * divisor
    if dividend > 2 * divisor  dividend -= 2 * divisor
    if dividend > 1 * divisor  dividend -= 1 * divisor
    quotient = dividend
    

    Just unroll as many times as there are bits in dividend. Make sure to be careful about those multiplies overflowing. This is just like your #2 except it takes log(n) instead of n iterations, so it is feasible to unroll completely.

提交回复
热议问题