Will this bitfield work the way I expect?

北战南征 提交于 2019-12-05 12:11:37

As the beginning of any union or struct will be aligned on a boundary, you cannot fit all your data in 32 bits this way. You should encapslulate your union and struct the other way round, as follows (attributes removed for readability):

typedef struct MyStruct {
   union {
      struct {
         unsigned state :  2;
         unsigned id    : 30;
      }
      struct {
         unsigned /* unused */ :  2; 
         unsigned bufferAIdx   : 16;
         unsigned bufferBIdx   : 14;
      };
   };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!