Keil Logo

C51: Bit Field Unions Don't Work as Expected


Information in this article applies to:

  • C51 Version 5.50 and later

SYMPTOMS

I 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;
  }

CAUSE

The 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.

RESOLUTION

In 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


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.