a number that can be written in 2n form will have only one bit set followed by n zeros on the right side of 1. When a number (N) divided by (2n), the bit positions corresponding to the above mentioned zeros will contribute to the remainder of division operation. An example can make it clear,
N = 87 (1010111 – binary form)
N%2 = N & (2-1) = 1010111 & 1 = 1 = 1
N = 87 (1010111 – binary form)
N%2 = N & (2-1) = 1010111 & 1 = 1 = 1
Modulus operation over exact powers of 2 is simple and faster bitwise ANDing. This is the reason, programmers usually make buffer length as powers of 2.
Read full article from Optimization Techniques | Set 1 (Modulus) | GeeksforGeeks
No comments:
Post a Comment