当前位置:网站首页>Share several methods of managing flag bits in C program
Share several methods of managing flag bits in C program
2022-07-28 05:12:00 【Xiao He Online】
One 、 brief introduction
In embedded development , Inevitably, a lot of flag bit processing will be involved , Especially playing with SCM 、 Bare metal development friends , For example, when cooperating with some modules for joint commissioning, you will encounter whether various signals are in place 、 Success and so on , And most of these signals are bool type ,1 individual bit You can identify . Of course , If only a few signs , Just take one uint8_t It won't affect anything to identify by shaping , But if there are too many, it seems to be more useless RAM 了 . In order to better manage these flag bits , There are several ways for you to better manage these flags .
Two 、 The bit field directly identifies
Using bit fields is a direct and convenient way to manage these flag bits , The code is as follows :
typedef union _tag_SystemFlag
{
uint16_t all;
struct
{
uint16_t Run :1;
uint16_t Alarm :1;
uint16_t Online :1;
uint16_t TimerOver :1;
uint16_t Reserver :12;
}bit;
} uSystemFlag;
uSystemFlag unSystemFlag;
int main(int argc, char *argv[]) {
unSystemFlag.all = 0x00; // System flag clear
unSystemFlag.bit.Run = 1; // Set up
unSystemFlag.bit.Alarm = 1;
unSystemFlag.bit.Online = 1;
unSystemFlag.bit.TimerOver = 1;
unSystemFlag.bit.Run = 0; // Zero clearing
unSystemFlag.bit.Alarm = 0;
unSystemFlag.bit.Online = 0;
unSystemFlag.bit.TimerOver = 0;
return 0;
}
The operation of these flag bits is nothing more than setting 、 Zero clearing , And three ways of reading .
However, such an operation mode in the code is not intuitive enough in terms of statement or semantic expression .
I often talk about , Code can not write comments , But each of your variables 、 Function names, etc. need to be intuitive enough , So many friends are used to encapsulating these signs .
3、 ... and 、 enumeration + displacement
For better expression, flag bits are generally further encapsulated , As shown in the following code :
typedef enum _tag_Flag {
cEmRun = 0,
cEmAlarm,
cEmOnline,
cEmTimerOver
}emSystemFlag;
uint16_t SystemFlag ;
// Set up
void SetFlag(emSystemFlag flag)
{
SystemFlag |= ((uint16_t)0x01) << flag;
}
// eliminate
void ClrFlag(emSystemFlag flag)
{
SystemFlag &= ~(((uint16_t)0x01) << flag);
}
// Get status
uint8_t GetFlag(emSystemFlag flag)
{
return (((SystemFlag & (((uint16_t)0x01) << flag)) != 0)? true:false);
}
int main(int argc, char *argv[]) {
SetFlag(cEmAlarm);
if(GetFlag(cEmAlarm) == true)
{
printf("ClrFlag\r\n");
ClrFlag(cEmAlarm);
}
else
{
printf("SetFlag\r\n");
SetFlag(cEmAlarm);
}
return 0;
}
Of course , Encapsulation into functions is relatively time-consuming , But the code will also be easier to understand , If you really can't tolerate the time consumption caused by function encapsulation , Change the function into macro code fragment or introverted function ( If the compiler supports ) It's also possible .
Four 、 Macro list
I have introduced it to you before , Use macros to automatically generate various code fragments , To make the code more compact . Of course, the readability will be relatively reduced , But you don't need to think too much about repetitive code .
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
typedef signed char int8_t;
typedef int int16_t;
#define true 1
#define false 0
// Macro list
#define TAG_LIST(tag) \ tag(Run)\ tag(Alarm)\ tag(Online)\ tag(TimerOver)
// Enumeration processing
#define DEFINE_TAG(_tag) _tag,
enum Flag {
None = 0,
TAG_LIST(DEFINE_TAG)
EmMAX
};
#undef DEFINE_TAG
// Bit definition variable
uint16_t SysFlag = 0x0000;
// General method definition
uint8_t GetFlags(uint16_t mask)
{
return ((SysFlag & mask) != 0)? true:false;
}
void SetFlags(uint16_t mask)
{
SysFlag |= mask;
}
void ClrFlags(uint16_t mask)
{
SysFlag &= ~mask;
}
// Automatically generate three types of function definitions
#define FLAG_Operater(flag) \ uint8_t get##flag() {
\ return GetFlags(1 << flag);\ }\ void set##flag() {
\ SetFlags(1 << flag);\ }\ void clr##flag() {
\ ClrFlags(1 << flag);\ }
// Inverse function correlation
TAG_LIST(FLAG_Operater)
int main(int argc, char *argv[]) {
setRun();
setAlarm();
if(getAlarm() == true)
{
printf("set \r\n");
}
else
{
printf("clr \r\n");
}
return 0;
}
If you have a friend who has handled similar code before , It should be easy to see this code , If a little strange , You can understand it layer by layer .
Its main function is , Through macro replacement and code splicing symbols , Automatically generate general code snippets . The advantage of this is , We no longer need to define a lot of setflag、clrflag、getflag Such as function .
Through the above code, when we go to TAGLIST Add an identifier to the macro , A series of related operation functions can be generated .
In this way, the code can be simplified , At the same time, it can also avoid some errors caused by manual coding .
边栏推荐
- Why is MD5 irreversible, but it may also be decrypted by MD5 free decryption website
- MySQL(5)
- Program life | how to switch to software testing? (software testing learning roadmap attached)
- 类和对象【中】
- Struct模块到底有多实用?一个知识点立马学习
- MySQL(5)
- I interviewed a 38 year old programmer and refused to work overtime
- Do you know several assertion methods commonly used by JMeter?
- [internal mental skill] - creation and destruction of function stack frame (C implementation)
- Comprehensively analyze the differences between steam and maker Education
猜你喜欢

CPU and memory usage are too high. How to modify RTSP round robin detection parameters to reduce server consumption?

【CVPR2022】Lite Vision Transformer with Enhanced Self-Attention

数据库日期类型全部为0

Research on the design of robot education in stem course

Melt cloud x chat, create a "stress free social" habitat with sound

The default isolation level of MySQL is RR. Why does Alibaba and other large manufacturers change to RC?

Design and development of C language ATM system project

Reading notes of SMT practical guide 1

C language classic 100 question exercise (1~21)

Keil Chinese garbled code solution
随机推荐
微服务故障模式与构建弹性系统
Can plastics comply with gb/t 2408 - Determination of flammability
Handling of web page image loading errors
What is the core value of testing?
如何在 FastReport VCL 中通过 Outlook 发送和接收报告?
【CVPR2022】Lite Vision Transformer with Enhanced Self-Attention
Pipe /createpipe
RT_ Use of thread message queue
Duoyu security browser will improve the security mode and make users browse more safely
Professor dongjunyu made a report on the academic activities of "Tongxin sticks to the study of war and epidemic"
Mysql基本查询
Activation functions sigmoid, tanh, relu in convolutional neural networks
UI automation test farewell from now on, manual download browser driver, recommended collection
阿里怎么用DDD来拆分微服务?
Dynamic SQL and paging
分享几种管理C程序中标志位的方法
Using RAC to realize the sending logic of verification code
From the basic concept of micro services to core components - explain and analyze through an example
Evolution of ape counseling technology: helping teaching and learning conceive future schools
How to successfully test php7.1 connecting to sqlserver2008r2