bit field in struct

1. What is a bit segment

A bit-field defines the space occupied by member variables in a structure (or union) in units of bits.

Note: 1. The members of the bit field must be int, unsigned int or signed int, char

               2. The member name of the bit field is followed by a colon and a number

struct A
{
    int a :2;  //a占两个bit位
    int b : 5;
    int c : 10;
    int d : 30;
}

2. Memory allocation of bit segment

        1. The space of the bit segment is opened up with 4 bytes (int) or 1 byte (char) as needed

        2. Bit fields are not cross-platform, and portable programs should avoid using bit fields

        3. A bit segment must be stored in the same storage unit and cannot span two storage units

        Example: In VS, the above A structure is placed as shown below.

        First place a, b, c, the remaining space is not enough to put d, and then open an int, put d, so the size of the A structure is 8 bytes

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqM55CD5oKs6ZOD5pyo5Li2,size_20,color_FFFFFF,t_70,g_se,x_16

The free space of the first storage unit in the figure below cannot hold a5, and another storage unit needs to be opened.

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LqM55CD5oKs6ZOD5pyo5Li2,size_20,color_FFFFFF,t_70,g_se,x_16

 

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_63742310/article/details/123749908
Bit
BIT