It is easy to "switch" between 0 and 1 in the following way:
int i = 0;
i = (++i) % 2; // i = 1
i = (++i) % 2; // i = 0
Similarly, I found that it is possible to "switch" between 3 and 5:
int i = 3;
i = (((i * 2) - 1) % 3) + 3; // i = 5
i = (((i * 2) - 1) % 3) + 3; // i = 3
Whereas this feels cumbersome, I am searching for a more concise way to do it. Can it be simplified? If so, how? I am actually using this for something, by the way.
Much shorter:
int i = 3;
i = 8 - i;
i = 8 - i;
And of course, for your 0/1 toggle, you should do this:
int i = 0;
i = 1 - i;
i = 1 - i;
And in general, for an a
/b
toggle, do this:
int i = a;
i = (a + b) - i;
i = (a + b) - i;
How does that work? Well, a + b - a
is b
, and a + b - b
is a
. :-D
Another way is to use XOR, because a ^ (a ^ b) == b
and b ^ (a ^ b) == a
:
int i = 3;
i ^= 3 ^ 5; // i == 5
i ^= 3 ^ 5; // i == 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With