ARM Technical Support Knowledge Articles

UNION INVOLVING A BITFIELD IS THE WRONG SIZE

Applies to: General Topics

Answer


Information in this article applies to:


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.

Article last edited on: 2005-07-19 10:21:13

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential