ARM Technical Support Knowledge Articles

BIT FIELD UNIONS DON'T WORK AS EXPECTED

Applies to: C51 C Compiler

Answer


Information in this article applies to:


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

Article last edited on: 2005-07-25 11:20:59

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