Keil Logo

GENERAL: UNION INVOLVING A BITFIELD IS THE WRONG SIZE


Information in this article applies to:

  • C166 Version 3.12
  • C166 Version 4.02
  • C251 Version 2.14
  • C51 Version 5.50

QUESTION

I have declared the following union:

union
{
  struct
  {
    unsigned x : 4;
    unsigned y : 4;
  } nibble;
  unsigned char abyte;
} value;

When I build my project and examine the map file, I see that the union occupies two bytes, but I want it to only occupy one. Why is the compiler wasting a precious byte of data memory?

ANSWER

The reason is that you declared bitfields as 'unsigned'. This defaults to 'unsigned int'.

A union's size accommodates the largest object. In this case, the structure contains an unsigned int (only one unsigned int because there are less than 16 bits specified in total). The size of an unsigned int is two bytes.

To use memory more efficiently, declare your union specifying unsigned chars for the bitfields:

union
{
  struct
  {
    unsigned char x:4;
    unsigned char y:4;
  } nibble;
  unsigned char abyte;
} value;

It then occupies a single byte.

MORE INFORMATION

Refer to a good C book, such as "The C Programming Language" by Kernighan & Ritchie, for more information on using bitfields, structures and unions.

FORUM THREADS

The following Discussion Forum threads may provide information related to this topic.

Last Reviewed: Tuesday, July 19, 2005


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.