| |||||
Technical Support Support Resources
Product Information | C51: BIT FIELD UNIONS DON'T WORK AS EXPECTEDInformation in this article applies to:
SYMPTOMSI have created a union of a bit field structure and an unsigned integer. When I set bit 0 of the unsigned int, the corresponding bit field is not set.
struct bit_st
{
unsigned char bit_0 : 1;
unsigned char bit_1 : 1;
unsigned char bit_2 : 1;
unsigned char bit_3 : 1;
unsigned char bit_4 : 1;
unsigned char bit_5 : 1;
unsigned char bit_6 : 1;
unsigned char bit_7 : 1;
unsigned char bit_8 : 1;
unsigned char bit_9 : 1;
};
union bit_un
{
unsigned int number;
struct bit_st bits;
};
void main (void)
{
union bit_un x;
x.number = 1;
}
CAUSEThe 8051 is a big endian architecture (opposite of all other Intel chips). This means that the MSB comes first and the LSB comes last. Your assignment sets bit 0 in the second byte of the union. The bit field bit_0 is located at bit 0 in the first byte of that union. RESOLUTIONIn your example, to set the bit field bit_0, you would need to change your assignment from: x.number = 1; to: x.number = 0x0100; SEE ALSO
FORUM THREADSThe following Discussion Forum threads may provide information related to this topic.
Last Reviewed: Monday, July 25, 2005 | ||||
| |||||