I have minimize cost of calculating modulus in C. say I have a number x and n is the number which will divide x
when n == 65536 (which happens to be 2^16):
m
x mod 65536 is only equivalent to x & 0xffff if x is unsigned - for signed x, it gives the wrong result for negative numbers. For unsigned x, gcc does indeed optimise x % 65536
to a bitwise and with 65535 (even on -O0, in my tests).
Because 65521 is not a power of 2, x mod 65521 can't be calculated so simply. gcc 4.3.2 on -O3 calculates it using x - (x / 65521) * 65521
; the integer division by a constant is done using integer multiplication by a related constant.