We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
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
ad 1) An unsigned (int) occupies 2 bytes on the C51, you can't shrink this by specifying a bitfield size.
ad 2) If you use unsigned char for the fields in struct setbit, the union will take 1 byte and everything works fine:
union BPS_FORMAT { unsigned char getbyte; struct { unsigned char StopBitLen :1;//0 unsigned char X :1;//1 unsigned char DataLen0 :1;//2 unsigned char DataLen1 :1;//3 unsigned char PE :1;//4 unsigned char Parity0 :1;//5 unsigned char Parity1 :1;//6 unsigned char M :1;//7 }setbit; }test;
Dear Thomas ! Thank You WERY MUCH! I aways think that bit struct must been defined like "unsigned soso :num " Now I understand that "unsigned " with nothing mean "unsigned int" 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