C 的 位字段
等级 4249 次按键
使用位字段将多个值高效地打包到单个结构体中。
C 代码
// 带位字段的结构体用于紧凑存储1struct Flags { // active标志的1位(0或1)2 unsigned int active : 1; // ready标志的1位3 unsigned int ready : 1; // error标志的1位4 unsigned int error : 1; // mode的4位(0-15)5 unsigned int mode : 4;6};7 // 按成员顺序赋值:active=1,ready=0,error=0,mode=58struct Flags f = {1, 0, 0, 5};// 位字段像普通成员一样读取:1和59printf("Active: %d\n", f.active);10printf("Mode: %d\n", f.mode);// 7个位可以放进一个unsigned int:常见编译器上为4字节11printf("Size: %lu bytes\n", sizeof(f));运行结果
Active: 1 Mode: 5 Size: 4 bytes
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C 代码中需要输入的符号及其出现次数。
;× 9:× 7,× 6"× 6(× 4)× 4\× 3%× 3.× 2{× 2