What's the most compact way to store a ternary value?
c
Solution
Base 3
0, 1, 2
10, 11, 12, /* 3, 4, 5 in base 10 */
20, 21, 22 /* 6, 7, 8 */
100, 101, 102 /* 9, 10, 11 */
...
Problem
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?