I need to have my integer counter have values from 1 to 6 inclusive in wrap around fashion. Namely starting from 1, I count to 6 and go back to 1. I wonder if it’s possible to achieve using some sort of bitwise logic. Of course it’s trivial with if statement as below but I am wondering about one liner 🙂
int counter = 1;
for...
do something
if (counter++ == 7) counter = 1;
Addition:
Here is why I want 1 liner:
byte output = (byte)((inputByte & 0xF8) | counter++);
Use the modulo operator.
To use real bitwise operations your modulo must be a power-of-2 which is not the case here.
PS: If your counter started at 0 instead of 1, you wouldn’t need the second
++counterand would write something like :PPS: Note that generally an
ifperforms faster than a modulo, tho.