问题
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?
回答1:
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.
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.
回答2:
The Visual Studio 2008 compiler docs indicate:
The ordering of data declared as bit fields is from low to high bit
From "C++ Bit Fields", MSDN C++ Language Reference, Visual Studio 2008 version
回答3:
If you're asking about which bits in myBitField are stored in which bits of the byte in memory, that's explicitly undefined by the C standards. You'll have to learn by experimentation. It's probably worthwhile, if you're doing something where this actually matters, to instead use an approach where you #define field1
as a hex value (for example, 0x40
or 0x02
) and put it where you want it.
来源:https://stackoverflow.com/questions/4547472/which-end-of-a-bit-field-is-the-most-significant-bit