A little bit of knowledge about the median field in the C struct. Recently, when reading data, I encountered a special operation in the struct --Bit domainIn the following program, I will give a brief introduction based on my own understanding. The program is only used to understand the nature of bit domains. Some compilers may report errors during runtime.
The program code is as follows (written in C ++). The compiler uses C-free, and the integer variable occupies 4 bytes. (Please correct me if you have encountered any errors .)
1 #include<iostream> 2 using namespace std; 3 4 struct bit { 5 int a:3; 6 int b:2; 7 int c:3; 8 }; 9 10 int main () {11 struct bit s;12 char *c = (char*)&s;13 cout<<sizeof(s)<<endl;14 *c = 0x99;15 *(c+1) = 0x97;16 cout<<s.a<<endl<<s.b<<endl<<s.c<<endl;17 return 0;18 }
Line 5-7 of the program uses the bitfield. Although the members A, B, and C are integers, they explicitly limit the actual length. where A is three binary digits, B is two binary bits, and C is three binary bits. The execution result of the program is as follows:
The first one indicates the length of the struct. Because the three Members do not actually occupy 4 bytes, the actual length is not 12. The following figure shows the actual storage relationships of A, B, and C,Bit field variables are stored in reverse order in actual storage(I don't know why), the actual storage condition is that the three variables constitute exactly the length of one byte. The program has 14th rows, * C = 0x99, then: a = 001b, B = 11b, c = 100b. Because the three numbers are all integer types, the default value is signed. Therefore, a is 1, B is-1, and C is-4.
If so, if the length of the three variables is more than 8 binary bits, change the struct to the following (change the binary bits of B to 3 ):
1 struct bit {2 int a:3;3 int b:3;4 int c:3;5 };
In this case, how should we store it? Since one byte is insufficient to store three variables, is C stored in two bytes or directly at the low level of the next byte? Run the preceding program and the result is as follows:
The result of C is-2. If it is stored in the next byte, c = 111B, the corresponding integer number should be-1, but the actual value is-2, which means this is not the case. In this way, c = 110b, Which is exactly-2. For further confirmation, change the value assignment operation for line 1 of the program to: * C = 0x59;
The result is as follows:
This indicates that it is stored in two bytes, and the storage location is as follows:
Different compilers may have different processing methods.
C struct median Field