Possible Duplicate:
Why is modulo operator necessary?
I need help understanding how does & give the modulus? I am working on an assignment to use memory access times to determine the cache sizes. Currently I am getting wierd results for the L3 size. I think it has something to do with & only working well for powers of 2, or something like that? So I want to understand how it actually works
lengthMod = 1024/sizeof(int) - 1;
for (unsigned int k = 0; k < REPS; k++) {
data[(k * 16) & lengthMod]++;
}
Will & always work? Or does it only work with some values? What actually happens for other values?
To expand on the other answers, if you take the modulus of a positive number and a positive power of 2 (i.e.
a % bwherebis a power of 2 andaandbare positive), you can effectively replace the%operator with the&operator (and subtract 1 from b, so it becomesa & (b - 1)).This is because the
&operator does a bit-wise mask, and the result of a number mod a power of two is just going to be the lower bits of that number.This only works when the right hand argument is a power of two and both numbers are positive. Otherwise, use the
%operator.