C language special structure--Application of bit field (bit segment)

We usually make a structure with some related data, which is very convenient and more readable when writing programs. Some data does not need to occupy a complete byte when stored, but only needs to occupy one or a few binary bits. For example, switch, enable, alarm, etc., only use 0 and 1.

In order to save storage space and make processing easy, C language provides a data structure called "bit field" or "bit segment". The so-called "bit field" is to divide the binary bits in a byte into several different areas and specify the number of bits in each area. Each domain has a domain name that allows operations by domain name in the program. In this way, several different objects can be represented by a binary bit field of one byte.

Example:

typedef unsigned char RS_U8;

 typedef struct
 {
    RS_U8 a:1;    //bit 0
    RS_U8 b:4;    //bit 1 ~ bit 4
    RS_U8 c:3;    //bit 5 ~ bit 7
}RS_STRUCT_ABC;

 typedef union
 {
    RS_STRUCT_ABC s;
     RS_U8 data;
 }RS_UNION_ABC;

 int main()
 {
     RS_UNION_ABC test;

    test.s.a=1;
     test.s.b=2;
     test.s.c=3;

     printf("a=%d, b=%d, c=%d, data=0x%.2X\n",test.s.a, test.s.b, test.s.c, test.data);

     return 0;
 }

Desired result:

 Program running results: a=1, b=2, c=3, data=0x65

Example warning:

typedef unsigned char RS_U8;

typedef struct
 {     RS_U8 low_power:1; //bit 0 underpower     RS_U8 over_power:1; //bit 1 overpower     RS_U8 c:1; //bit 2     RS_U8 d:1; //bit 3     RS_U8 e:1; // bit 4     RS_U8 f:1; //bit 5    RS_U8 g:1; //bit 6     RS_U8 h:1; //bit 7  }STRUCT_ALARM;








It only takes one byte to complete 8 alarm data, thereby saving space.

It is also very simple to apply, such as:

STRUCT_ALARM PA_Alarm; //Define structure

PA_Alarm.low_power=1; //Alarm assignment

Guess you like

Origin blog.csdn.net/llq_the7/article/details/127535863