I'm working on writing a simple flash file system, and I need to store one of three states for each page in the flash device:
FREE
INVALID (ready to be freed)
VALID
If it were only two possible states, I'd use a bitmap for sure (memory is a concern). But what's the most compact way of holding these values in this case?
The only thing I can think of are packing four 2-bit values into a char
and using bitmasks to operate on each value.
For example (wrote this quickly, so there's no guarantee it works perfectly):
#define FREE 0x0 // 0b00
#define INVALID 0x1 // 0b01
#define VALID 0x2 // 0b10
char state[NUM_ITEMS/4];
void set_state(int item_num, int state) {
int idx;
char tmp;
idx = item_num / 4;
tmp = state[idx];
tmp &= ~(0x3 << (item_num % 4));
tmp |= (state << (item_num % 4));
state[idx] = tmp;
}
int main(void) {
//...
set_state(6, INVALID);
//...
return 0;
}
Is there another option I'm unaware of?