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
The free space of the first storage unit in the figure below cannot hold a5, and another storage unit needs to be opened.