Assembly mod algorithm on processor with no division operator

前端 未结 8 1898
挽巷
挽巷 2020-12-09 10:57

I need to implement a simple macro that finds the modulo of two numbers on a processor that doesn\'t have a division operator (think ARM). I could use division by repeated s

8条回答
  •  轮回少年
    2020-12-09 11:30

    mod can be computed bit by bit:

    int r = 0;
    int q = 0;
    for (int i = sizeof(n) * 8 - 1; i >= 0; --i) {
      r <<= 1;
      r |= (n >> i) & 1;
      if (r > d) {
        r -= d;
        q |= 1 << i;
      }
    }
    return r;
    

    That gives you the remainder, q would be the quotient. If you have bsrl instruction, you can set a better high bound for i, since you can start at the most significant bit only.

提交回复
热议问题