2 bits size variable

前端 未结 3 1701
夕颜
夕颜 2020-12-19 10:48

I need to define a struct which has data members of size 2 bits and 6 bits. Should I use char type for each member?Or ,in order not to waste a memory,can I use

3条回答
  •  春和景丽
    2020-12-19 10:52

    Personally I prefer shift operators and some macros over bit fields, so there's no "magic" left for the compiler. It is usual practice in embedded world.

    #define SET_VAL2BIT(_var, _val) ( (_var) | ((_val) & 3) )
    #define SET_VAL6BIT(_var, _val) ( (_var) | (((_val) & 63)  << 2) )
    
    #define GET_VAL2BIT(_var) ( (_val) & 3)
    #define GET_VAL6BIT(_var) ( ((_var) >> 2) & 63 )
    
    static uint8_t my_var;
    
    <...>
    SET_VAL2BIT(my_var, 1);
    SET_VAL6BIT(my_var, 5);
    int a = GET_VAL2BIT(my_var); /* a == 1 */
    int b = GET_VAL6BIT(my_var); /* b == 5 */
    

提交回复
热议问题