I have an Arduino application (well, the library itself), in which there are several status flags, and initially I just declared them as ints (well, uint8_t and 8 bits unsigned in this case). But I could combine them all into a single whole and use bit masks to set and check the status.
An example of the first:
if (_shift == HIGH) { _shift = LOW; } else { _shift = HIGH; }
last example
#define SHIFT_BIT 0 if (bitRead(_flags, SHIFT_BIT) == HIGH) { bitWrite(_flags, SHIFT_BIT, LOW); } else { bitWrite(_flags, SHIFT_BIT, HIGH); }
The former reads better, but the latter is more effective (space and time). Should time and time effectively win in this situation, or is it some kind of optimization that should only happen when necessary?
(Added)
For completeness, here is the definition of the wiring of these Write bits, etc. macros:
#define bitRead(value, bit) (((value) >> (bit)) & 0x01) #define bitSet(value, bit) ((value) |= (1UL << (bit))) #define bitClear(value, bit) ((value) &= ~(1UL << (bit))) #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
source share