What is the most compact way to store triple value?

I am working on writing a simple flash file system, and I need to save one of three states for each page of the flash device:

FREE
INVALID (ready to be freed)
VALID

If these were only two possible states, I would probably use a bitmap (memory is a problem). But what is the most compact way to store these values ​​in this case?

The only thing I can think of is to pack four 2-bit values ​​in charand use bitmasks to work with each value.

For example (it is written quickly, so there is no guarantee that it works fine):

#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 that I don't know about?

+4
source share
4 answers

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 */
...
+3
source

() , , - 5 () . :

FFFFF (0)
FFFFI (1)
FFFFV (2)
FFFIF (4) 
...
VVVVV (242)

243 , 8- (2 ** 8 = 256). , 10 2 , 15 3 ..

+1

, 8- char. x, x*3, x*3*3, - x*3*3*3... ..

char, y, y % 3. , (y/3) % 3, (y/(3*3)) % 3 ... ..

, 4 char, .

0

C99 _Bool ( bool _Bool.), 0 1 ( , 1 , a char (1 )).   , - .   , 3 ( ) .

Interesting data: "[...] that nothing is required for a byte to be 8 bits - in fact, in fact, the only references that the C standard makes for a byte are like the amount of storage needed to store the char. It requires char to be able to hold at least 255 unique values, so it must be at least 8 bits, but it can be more than necessary if desired. "

Extract from the art of quora

-1
source

Source: https://habr.com/ru/post/1676307/


All Articles