首页 > 代码库 > 【读书笔记】C Primer Plus ch.15位运算 示例程序15.3 定义并使用字段

【读书笔记】C Primer Plus ch.15位运算 示例程序15.3 定义并使用字段

通常,把位字段作为一种更紧凑储存数据的方式。

 

程序清单 15.3 fields.c

 1 #include <stdio.h>
 2 #include <stdbool.h>
 3 // 线的样式
 4 #define SOLID 0 // 实线
 5 #define DOTTED 1 // 点线
 6 #define DASHED 2 // 虚线
 7 // 三原色
 8 #define BLUE 4
 9 #define GREEN 2
10 #define RED 1
11 // 混合色
12 #define BLACK 0
13 #define YELLOW (RED|GREEN)
14 #define MAGENTA (RED|BLUE)
15 #define CYAN (GREEN|BLUE)
16 #define WHITE (RED|GREEN|BLUE)
17 
18 const char * colors[8] = { "black","red","green","yellow",
19 "blue","magenta","cyan","white" };
20 
21 struct box_props {
22     bool opaque : 1; // 方框是否透明
23     unsigned int fill_color : 3;
24     unsigned int : 4; // 每个字节间的空隙用未命名字段填充
25     bool show_border : 1; // 边框显示或隐藏
26     unsigned int border_color : 3;
27     unsigned int border_style : 2;
28     unsigned int : 2;
29 };
30 
31 void show_settings(const struct box_props * pb)
32 {
33     printf("Box is %s.\n", pb->opaque == true ? "opaque" : "transparent");
34     printf("The fill color is %s.\n", colors[pb->fill_color]);
35     printf("Border %s.\n", pb->show_border == true ? "shown" : "not shown");
36     printf("The border color is %s.\n", colors[pb->border_color]);
37     printf("The border style is ");
38     switch (pb->border_style)
39     {
40     case SOLID:
41         puts("solid.");
42         break;
43     case DOTTED:
44         puts("DOTTED.");
45         break;
46     case DASHED:
47         puts("dashed.");
48         break;
49     default:
50         puts("unknown type.");
51     }
52 }
53 
54 int main(void)
55 {
56     struct box_props box = { true,YELLOW,true,GREEN, DASHED };
57 
58     puts("Original box settings:");
59     show_settings(&box);
60 
61     box.opaque = false;
62     box.fill_color = WHITE;
63     box.border_color = MAGENTA;
64     box.border_style = SOLID;
65     puts("\nModified box settings:");
66     show_settings(&box);
67 
68     return 0;
69 }

 

【读书笔记】C Primer Plus ch.15位运算 示例程序15.3 定义并使用字段