Hi all. I recently stumbled across the following code:
What this (supposedly??) does is continuously call some_operation and increment val until val is an integer multiple of 8. I understand binary and use of the bitwise-operator, I just can't convince myself that this is 'true' for and works properly for all integer m such where (m*8) < val < (m+1)*8 . Is this some kind of trick only possible because 8 is a power of 2? The formula clearly does not work if we do (++val & 4) until val is a multiple of 5, as this test will fail for decimal values 1, 2, and 3..
} while (++val & 7);
Moreover, I need to expand this functionality for any integer n > 1, not just n = 8. Obviously the trivial solution is
But I have had it burned into my head that the modulo operator is expensive. Is there a better, more efficient solution for this problem?
} while( (++val % m) != 0 );