The maximum size of all basic data types is 10 bytes;
We can customize the Data Type-"structure". By combining several types, a type can be much larger.
We know that a byte consists of eight bits. Can we narrow down a type to a bit level?
The "bit field" in the structure is in bit, which is the smallest unit of the computer and the size is 1/8 of the char type.
The bit fields defined in the following example have 1-4 bit sizes, and the 1 bit field can only contain two numbers (0, 1 ), the number of 4-bit fields can only be dropped by 16:
1. struct can contain bit fields:
# Include <stdio. h> int main (void) {struct bit {unsigned A: 1;/* 1 bit; value range: 0-1 */unsigned B: 2;/* 2 bit, value Range: 0-3 */unsigned C: 3;/* 3 bit; value range: 0-7 */unsigned D: 4;/* 4 bit; value range: 0-15 */} B; B. a = 1; B. B = 3; B. C = 7; B. D = 15; printf ("% d, % d \ n", B. a, B. b, B. c, B. d); getchar (); Return 0 ;}
In the above example, the type of the bit field is specified as an unsigned integer (unsigned INT). I tried to make it consistent as long as it is an integer.
If we define eight fields and each field is 1 bit, we can detail a byte well, for example:
11111111b = 255;
100000001b = 1;
Listen 1111b = 15;
01111111b = 127;
The following example usesProgramThe above descriptions are implemented:
2. 8 bits form an unsigned char Number:
# Include <stdio. h> int main (void) {struct bit {int B8: 1; int B7: 1; int B6: 1; int B5: 1; int B4: 1; int B3: 1; int B2: 1; int B1: 1;} B; unsigned char * P = NULL; B. b1 = 1; B. b2 = 1; B. b3 = 1; B. b4 = 1; B. b5 = 1; B. b6 = 1; B. b7 = 1; B. b8 = 1; P = (unsigned char *) & B; printf ("% d \ n", * P);/* 255 */B. b1 = 0; B. b2 = 0; B. b3 = 0; B. b4 = 0; B. b5 = 0; B. b6 = 0; B. b7 = 0; B. b8 = 1; P = (unsigned char *) & B; printf ("% d \ n", * P);/* 1 */B. b1 = 0; B. b2 = 0; B. b3 = 0; B. b4 = 0; B. b5 = 1; B. b6 = 1; B. b7 = 1; B. b8 = 1; P = (unsigned char *) & B; printf ("% d \ n", * P);/* 15 */B. b1 = 0; B. b2 = 1; B. b3 = 1; B. b4 = 1; B. b5 = 1; B. b6 = 1; B. b7 = 1; B. b8 = 1; P = (unsigned char *) & B; printf ("% d \ n", * P);/* 127 */getchar (); Return 0 ;}
3. There is no difference between the structure of fields containing bits and other structures. For example, fields of other types are included at the same time:
# Include <stdio. h> int main (void) {struct bit {unsigned B1: 1; unsigned B2: 1; float F ;} B; B. b1 = 0; B. b2 = 1; B. F = 3.14; printf ("% d, % d, % G \ n", B. b1, B. b2, B. f); getchar (); Return 0 ;}