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
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.