枚举+移位
为了更好的表达一般会对标志位进行进一步的封装,如下代码所示:
- 1typedef enum _tag_Flag {
- 2cEmRun = 0,
- 3cEmAlarm,
- 4cEmOnline,
- 5cEmTimerOver
- 6}emSystemFlag;
- 7
- 8uint16_t SystemFlag ;
- 9//置位
- 10void SetFlag(emSystemFlag flag)
- 11{
- 12 SystemFlag |= ((uint16_t)0x01) << flag;
- 13}
- 14//清除
- 15void ClrFlag(emSystemFlag flag)
- 16{
- 17 SystemFlag &= ~(((uint16_t)0x01) << flag);
- 18}
- 19//获得状态
- 20uint8_t GetFlag(emSystemFlag flag)
- 21{
- 22 return (((SystemFlag & (((uint16_t)0x01) << flag)) != 0)? true:false);
- 23}
- 24
- 25int main(int argc, char *argv[]) {
- 26
- 27 SetFlag(cEmAlarm);
- 28
- 29 if(GetFlag(cEmAlarm) == true)
- 30 {
- 31 printf("ClrFlag\r\n");
- 32 ClrFlag(cEmAlarm);
- 33 }
- 34 else
- 35 {
- 36 printf("SetFlag\r\n");
- 37 SetFlag(cEmAlarm);
- 38 }
- 39 return 0;
- 40}
当然,封装成函数是相对比较耗时的,不过代码也会更加的易懂,如果确实容忍不了函数封装带来的时间消耗,把函数修改为宏代码片段或者内敛函数(前提是编译器支持)也是可行的。
|