哪一个位字段是最重要的一点?

我正在使用Visual Studio 2008为 Windows XP / Vista / 7编写C应用程序.我的一些结构使用一个位字段,如示例所示.
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;

该领域的哪一端是最重要的一点?

解决方法

C99标准6.7.2.1/10(强调我的):

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.

因此,您的编译器实现必须记录顺序.

然而,关于如何实现位域是实现定义或未指定的,使用它们以便携式方式对硬件,有线协议或文件格式位字段进行建模是不值得尝试的麻烦.

如果你想让你的“位字段”对程序外部的东西进行建模(像上面的那样),使用显式掩码,使用标准的位运算符(|,’&,〜,& ;`等等).使用帮助内联函数(如果必须的话,甚至是宏),使您的代码更容易/更清晰.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...