This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

The bit struct in union

Hello!
I want to set one byte by bit.
the follow works. But:
(1) Why this union takes 2 bytes?

union BPS_FORMAT
{
        struct
        {
                unsigned format         :8;
        }getbyte;
        struct
        {
                unsigned StopBitLen     :1;//0
                unsigned X              :1;//1
                unsigned DataLen0       :1;//2
                unsigned DataLen1       :1;//3
                unsigned PE             :1;//4
                unsigned Parity0        :1;//5
                unsigned Parity1        :1;//6
                unsigned M              :1;//7
        }setbit;
}test;
      test.setbit.PE=1;
//now  test.getbyte.format=0x10 it works!
 x =sizeof(union BPS_FORMAT);
//x=2 !!!!Why? Why the union take 2 bytes,and it works!


(2)Why the follow do NOT work?

union BPS_FORMAT
{

        unsigned char getbyte;
        struct
        {
                unsigned StopBitLen     :1;//0
                unsigned X              :1;//1
                unsigned DataLen0       :1;//2
                unsigned DataLen1       :1;//3
                unsigned PE             :1;//4
                unsigned Parity0        :1;//5
                unsigned Parity1        :1;//6
                unsigned M              :1;//7
        }setbit;
}test;
      test.setbit.PE=1;
// BUT test.getbyte  still  = 0
//This union takes 2 byte too.


Why?
Thanks!
BaoHua Zhu

0