Incrementing and wrapping back to zero is easy:
i = (i + 1) % Max;
But decrementing is not as straight forward. Basically to decrement and wrap you usually find code like this:
i--;
if (i < 0)
i = Max;
How can we write the previous code without using if statements?
I know that probably bit-wise operators will be involved. Usually when I'm faced with such problems I try to come up with some equations with two terms A and B, then try to find the actual values of these two terms. For example:
i = A + B
if i
was in the range ]0, Max]
then we'd get:
i = 0 + B
and B = i-1
otherwise if i == 0
:
i = A + 0
and A = Max
similarly we can write:
i = i == 0 ? Max : i - 1;
How to write the previous equation without any ifs or ternary operators? I tried so many bit-wise operations and different arithmetic combos but to no avail.
Any ideas?