2

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.

  • 5
    When 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
  • 1
    The 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
  • 1
    The 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
  • 1
    Using 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 Answers1

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