-
Bit fields problem
Hi all,
I am experiencing a problem with bit fields. I have simplified my original code to a code snippet below:
In the code below, what is wrong with the static const initialization?
I am expecting name3 and name4 to have a value of 7 in variable num OR a value of 1 for a,b,c.
However I see only value of 1 for "a" only in those 2 cases.
The first two name1 and name2 work fine.
Code:
typedef union
{
struct
{
unsigned char a : 1,
b : 1,
c : 1,
: 5;
};
unsigned char num;
}STNAME;
static const STNAME c1 =
{
(0x07)
};
static const STNAME c2 =
{
(0x01 | 0x02| 0x03)
};
int _tmain(int argc, _TCHAR* argv[])
{
STNAME name1;
name1.a = 0x1;
name1.b = 0x1;
name1.c = 0x1;
STNAME name2;
name2.num=0x7;
STNAME name3;
name3 = c1; // does not assign 0x7 (or 1 to each of a,b,c)
STNAME name4;
name4 = c2; // does not assign 0x7(or 1 to each of a,b,c)
return 0;
}
Thanks .
-
My guess would be that if you assign 1 to a, and then print num, you get 128.
The bit-order for bit-fields is compiler dependant, so you would have to take that into account when ordering the bits in the bitfield struct.
--
Mats
-
> In the code below, what is wrong with the static const initialization?
You can't initialise a union IIRC.
Some compilers allow you to initialise the first member, in which case it would be something like
Code:
static const STNAME c1 =
{
{ 1, 1, 1 }
};
The rest is as matsp says.
Everything about bit-fields is implementation dependent. Trying to overlay a bit-field with a union with something else is never going to give you good answers you can rely on.