到底哪一个位字段是最显著位? [英] Which end of a bit field is the most significant bit?

查看:150
本文介绍了到底哪一个位字段是最显著位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写的Windows XP / Vista / 7的使用Visual Studio 2008中我的一些结构,使用一个位域,如图中的示例为C ++应用程序。

I'm writing a C++ application for Windows XP/Vista/7 using Visual Studio 2008. Some of my structures use a bit field, as shown in the example.

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;

哪个端领域是最显著位

Which end of the field is the most significant bit?

推荐答案

C99标准6.7.2.1/10(重点煤矿):

C99 standard 6.7.2.1/10 (emphasis mine):

这是实现可分配任何可寻址存储单元,大到足以容纳一个比特。如果有足够的空间保持,紧跟在一个结构的另一位字段位字段须包装到同一单元的相邻比特。如果没有足够的空间仍然存在,不适合一个位字段是否被放入下一个单元或重叠相邻单元是实现定义的。 单元(高阶到低阶或低阶到高阶)中位域的分配顺序是实现定义的。可寻址存储单元的排列是不确定的。

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.

因此​​,订单必须由你的编译器实现记录。

So, the order must be documented by your compiler implementation.

不过,这么多关于位域是如何实现的定义实现或未指定,使用他们的便携式时尚五金,线材协议或文件格式位字段模式是不值得的麻烦尝试。

However, so much about how bitfields are implemented are implementation defined or unspecified that using them to model hardware, wire-protocol, or file format bit fields in a portable fashion is not worth the trouble to attempt.

如果你希望你的位域的东西外部模型程序(如上面的东西),使用显式面具,设置和使用标准位运算符(清零位| ,'和; <<'等)。使用辅助内联函数(或者如果你一定要连宏),使这更容易/更清楚你的code。

If you want your 'bit fields' to model something external to your program (like the above things), use explicit masks, setting and clearing the bits using the standard bit-wise operators (|, '&,~,<<`, etc.). Use helper inline functions (or even macros if you must) to make this easier/clearer in your code.

这篇关于到底哪一个位字段是最显著位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆