I have an Arduino application (well actually a library) that has a number of status flags in it - and originally I simply declared them as ints (well uint8_t so 8 bit unsigned chars in this case). But I could have combined them all into one integer and used bitmask operations to set and test the status.
An example of the former:
if (_shift == HIGH)
{
_shift = LOW;
}
else
{
_shift = HIGH;
}
an example of the latter
#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 efficient (space and time). Should the space and time efficiency always win in this situation or is this a kind of optimization that should only happen when needed?
(Added)
For completeness here's the Wiring definition of those bitWrite 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))