Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which end of a bit field is the most significant bit?

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?

like image 960
Jim Fell Avatar asked Dec 28 '10 16:12

Jim Fell


1 Answers

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.

like image 111
Michael Burr Avatar answered Oct 12 '22 02:10

Michael Burr