Given two numbers a and b where b is of form 2k where k is unknown.What would be the efficient way of computing a%b using bitwise operator.
Asked
Active
Viewed 580 times
2
-
5When asking a homework question, show us a bit of effort on your side. What are your thoughts? Where are you having difficulties? – Oded Aug 15 '11 at 13:00
-
1The obvious solution works as long as _a_ is positive, but achieving the correct behavior of `%` for negative operands by pure bit fiddling is going to be complex. – hmakholm left over Monica Aug 15 '11 at 13:07
-
1The most efficient way is to use DIV, one assembly instruction with the modulus in the DX register. Why do it a more inefficient way! – QuentinUK Aug 15 '11 at 13:12
-
1Using DIV is actually the LEAST EFFICIENT way. DIV (even on modern x86 processors) uses much more logic and runs slower (when counting processor clock cycles) then the bit-wise logic op-codes. However, it is the 'simplest" solution. – Louis Ricci Aug 15 '11 at 13:39
1 Answers
3
a AND (b-1) == a%b (when b is 2^k)
ex. a = 11 (1011b), b = 4 (0100b)
11 / 4 = 2 R3
11 % 4 == 11 AND (4-1)
11 (1011b) AND 3 (0011b) == 3 (0011b)

Louis Ricci
- 20,804
- 5
- 48
- 62