C language in the combination of bit field and structure union use details

  • 2020-04-01 23:32:13
  • OfStack

For example:
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =



typedef union {
   byte Byte;
   struct {
      byte RAMHAL :1;
      byte :1;
      byte :1;
      byte RAM11 :1;
      byte RAM12 :1;
      byte RAM13 :1;
      byte RAM14 :1;
      byte RAM15 :1;
   } Bits;
   struct {
      byte :1;
      byte :1;
      byte :1;
      byte grpRAM_11 :5;
   }MergedBits;
} INITRMSTR;

There are three ways to assign values, such as directly to INITRMSTR

INITRMSTR = 0 xef;

Bit fields can also be assigned

INITRMSTR. Bits. RAM15 = 1;

It is also possible to assign a value to a bit field

INITRMSTR. MergedBits. GrpRAM_11 = 26

(26 is decimal, converted to binary is 11010, which directly means RAM_11 = 0, RAM_12 = 1, RAM_13 = 0, RAM_14 = 1, RAM_15 = 1)

Notice that in binary the order is from right to left, and in this structure it's from up to down.


Related articles: