1、使用位域 有些数据在存储时并不需要占用一个完整的字节,只需要占用一个或几个二进制位即可。
比如:管理一些标志位。 使用位域: struct {
unsigned char flag1:1;
unsigned char flag2:1;
unsigned char flag3:1;
unsigned char flag4:1;
unsigned char flag5:1;
unsigned char flag6:1;
unsigned char flag7:1;
unsigned char flag8:1;
} flags;
优于: struct {
unsigned char flag1;
unsigned char flag2;
unsigned char flag3;
unsigned char flag4;
unsigned char flag5;
unsigned char flag6;
unsigned char flag7;
unsigned char flag8;
} flags;
2、使用位操作代替除法和乘法使用位操作: uint32_t val = 1024;
uint32_t doubled = val << 1;
uint32_t halved = val >> 1;
优于: uint32_t val = 1024;
uint32_t doubled = val * 2
uint32_t halved = val / 2
|