2

Admittedly this is a very silly question, but one that I was thinking about the other day. Sometimes in source I see registers defined like so:

union
{
   uint8_t byte;
   struct
   {
      uint8_t bit1   :1;
      uint8_t bit2   :1;
      uint8_t bit3_4 :2;
      uint8_t rsvd   :4;
   } bitfield;
} SomeReg_t;

Other times I see just a standard struct:

struct
{
   uint8_t bit1   :1;
   uint8_t bit2   :1;
   uint8_t bit3_4 :2;
   uint8_t rsvd   :4;
} SomeReg_t;

I wrote a quick example to show what I mean:

https://onlinegdb.com/r1H3Xuqe4

The question is, in regard to bitfields, what are the differences in these two definitions. When would you use one vs the other for bitfields.

Birts
  • 149
  • 1
  • 8
  • 2
    Bitfields? See https://stackoverflow.com/questions/21350852/bit-fields-in-a-union-how-portable-is-this and https://stackoverflow.com/questions/46021790/are-there-reasons-to-avoid-bit-field-structure-members – Andrew Henle Dec 21 '18 at 14:29

1 Answers1

2

It is easy to explain

Union is handy if you want to read or assign the whole byte as well.

for example

typedef union
{
   uint8_t byte;
   struct
   {
      uint8_t bit1   :1;
      uint8_t bit2   :1;
      uint8_t bit3_4 :2;
      uint8_t rsvd   :4;
   } bitfield;
} SomeReg_t;

SomeReg_t reg;

reg.bitfield.bit1 = 1;
/*...*/
printf("The reg value is %hhx\n", reg.byte);


reg.byte = ReadFormPeriph();

if(reg.bitfield.rsvd == 0b1011)
{
    /* do something */
}
danglingpointer
  • 4,708
  • 3
  • 24
  • 42
0___________
  • 60,014
  • 4
  • 34
  • 74