C++ 2-bit bitfield arrays possible?

前端 未结 2 1081
走了就别回头了
走了就别回头了 2020-12-21 09:11

I have a struct of 2-bit bitfields like this:

struct MyStruct {
    unsigned __int32 info0  : 2;
    unsigned __int32 info1  : 2;
    unsigned __int32 info2          


        
2条回答
  •  星月不相逢
    2020-12-21 09:17

    If you can't use Paul R's answer for whatever reason, you can always use a custom accessor with a standard array :

    static unsigned __int8 infos[30]; // 240 bits allocated
    
    unsigned __int8 getInfo( unsigned short id_num )
    {
        return (infos[id_num/4] >> ((2*id_num) % 8) ) & 0x3;
    }
    // setInfo left as an exercise.
    

    (You may need to check the logic here, I haven't tested it.)

提交回复
热议问题