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
"Now I understand that 'unsigned' with nothing mean 'unsigned int'"
That much is standard ANSI 'C' - nothing specifically to do with Keil C51.
But bitfields are notoriously implementation-dependent - so do take the time to study the peculiarities of the Keil C51 implementation: www.keil.com/.../search.asp
In practice, with C51, I don't think you get any advantage with using bitfields over just doing it with bitwise mask operators - there's been plenty of discussion of it before, so do the 'Search'
If you do wand high-performance bit manipulation, look at the 8051's bit-addressing facilities: http://www.keil.com/support/man/docs/c51/c51_le_bit.htm http://www.keil.com/support/man/docs/c51/c51_le_bitaddrobj.htm http://www.keil.com/support/man/docs/c51/c51_le_bdata.htm
Mr.Neil Thanks a lot. Your ignorant student BaoHua Zhu