Today, I will talk about the bit field in C. It is still very useful in many places. It is not a good way to use 50 to solve the problem that can be solved by drawing 100.
Without further ado, let’s start with the code:
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure needs 8 bytes of space, but if we just store true/false, isn't it a bit wasteful to define such a variable. So C provides a better way of managing memory, that's what we're talking about. How to do it, see below:
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
How many bytes can be measured?
That's right, the first structure takes up 8 bytes of space and the second takes up 4 bytes of space.
This structure: the following number is the limit number of digits, so the latter number needs to be less than or equal to the type bit width of the variable.
Specifically listed:
The form of declaring a bit field within a structure is as follows:
struct
{
type [member_name] : width ;
};
The following is a description of the variable elements in the bit field:
type : Integer type, which determines how the value of the bit field is interpreted. The type can be integer, signed integer, or unsigned integer.
member_name: The name of the bit field.
width: The number of bits in the bitfield. The width must be less than or equal to the bit width of the specified type.
For example:
Kindergarten counts the age of students. If this structure is used, how should we do it?
If the age cannot exceed 7.
Then we give the structure:
struct
{
unsigned int age : 3;
} Age;
ok, limit 3 bits, that is, 2^3 = 8 (0~7)
int main( )
{
Age.age = 4;
printf( “Sizeof( Age ) : %d\n”, sizeof(Age) );
printf( “Age.age : %d\n”, Age.age );
Age.age = 7;
printf( “Age.age : %d\n”, Age.age );
Age.age = 8;
printf( “Age.age : %d\n”, Age.age );
return 0;
}
How it turned out:
True: 4, 7, 0
The structure definition above instructs the C compiler that the age variable will only use 3 bits to store this value, and if you try to use more than 3 bits, it can't be done.
If the compilation finds that there will be warnings, but the results will still come out, this tells us that the warnings still need to be eliminated.