C language structure position field

In C language, a structure bit field is a special structure member that allows you to define a binary bit field in a structure to store multiple Boolean or enumeration values ​​in a single byte.

Structure body fields are defined as follows:

struct {  
    unsigned int bit1: 1;   // 定义一个名为bit1的位域,占用1个二进制位  
    unsigned int bit2: 1;   // 定义一个名为bit2的位域,占用1个二进制位  
    unsigned int bit3: 2;   // 定义一个名为bit3的位域,占用2个二进制位  
    unsigned int bit4: 4;   // 定义一个名为bit4的位域,占用4个二进制位  
} my_bits;

In the above example, my_bitsthe structure contains four bit fields, occupying 1, 1, 2 and 4 binary bits respectively. These bitfields can store boolean or enumeration values, as shown below:

my_bits.bit1 = 1;    // 将bit1设置为1  
my_bits.bit2 = 0;    // 将bit2设置为0  
my_bits.bit3 = 3;    // 将bit3设置为3(占用2个二进制位的值)  
my_bits.bit4 = 0xF;  // 将bit4设置为0xF(占用4个二进制位的值)

Note that the order of the structure's bitfields depends on the endianness of the underlying machine, so different machines may store the bitfields in a different order. Additionally, the width of a bit field must be a compile-time constant, so variables cannot be used to define the width of a bit field.

Guess you like

Origin blog.csdn.net/MyLovelyJay/article/details/133283615