typedef struct myStruct_tag
{
BYTE myVar1;
WORD myVar2;
WORD myVar3;
union
{
struct
{
BYTE :1;
BYTE field1 :1;
BYTE field2 :1;
BYTE reserved :5;
} myBitField;
BYTE myVar4;
};
BYTE myVar5;
BYTE myVar6;
} myStruct_t;
该领域的哪一端是最重要的一点?
解决方法
An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains,a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains,whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
因此,您的编译器实现必须记录顺序.
然而,关于如何实现位域是实现定义或未指定的,使用它们以便携式方式对硬件,有线协议或文件格式位字段进行建模是不值得尝试的麻烦.
如果你想让你的“位字段”对程序外部的东西进行建模(像上面的那样),使用显式掩码,使用标准的位运算符(|,’&,〜,& ;`等等).使用帮助内联函数(如果必须的话,甚至是宏),使您的代码更容易/更清晰.