I have to program independent bits in a bitfield spanning multiple DWORDS. I am currently using a struct as follows
typedef struct _myStruct
{
union
{
struct
{
DWORD field1 : 16
DWORD field2 : 8
DWORD field3 : 8
};
DWORD value0;
};
union
{
struct
{
DWORD field4 : 32;
}
DWORD value1;
};
} myStruct;
I do this so that a programmer can access independent fields directly, and not remember the corresponding DWORD i.e. as myStruct.field1 etc.
This works well in Visual Studio, however GCC complains when I used unnamed structs and unions. To correct that I tried naming the unions and structs as below:
union _DW0
{
struct _BF
{
DWORD field1 : 16
DWORD field2 : 8
DWORD field3 : 8
} BF;
DWORD value0;
} DW0;
But now the access is not programmer friendly.. i.e. someone who tries to program this have to remember which DWORD each field belongs to. For eg: myStruct.DW0.field1
Is there a way to get around this?
Bitfields are inherently non-portable. When you write
DWORD field1 : 16;the standard does not determine whetherfield1should have the higher or lower 16 bits of the struct. On the other hand, if you use proper types and unions (which in your case suffice, since all your bitfields match a type in most platforms), that can be portable.Using C++11 types (you can alternatively use a library that has the proper types for your platform):