Moule Lin
← All notes

Replacing Modulo with Bitwise AND

Since bitwise operations are relatively efficient, in some cases, when b is 2 to the power of n, the following substitution holds:

a % b = a & (b-1)

notes:

For example, 14%8: taking the remainder is equivalent to extracting the low bits, and the largest possible remainder is 7. 14 in binary is 1110, 8 is 1000, and 8-1 = 7 is 0111. Since the low bits are now all 1, ANDing with 14 extracts exactly the remainder held in its low bits