C/C++|C/C++ int数与多枚举值互转的实现

在C/C++在C/C++的开发中经常会遇到各种数据类型互转的情况,正常的互转有:单个枚举转int数,int数转float数,float数转double数等。但是我们有时也会遇到多个枚举值与数字互转的情形(例如多个算法类型枚举开启标志转成数字,这个数字来表示多个标志位,按位来表示)。这样一个数字就能表示很多个标志位了,针对内存较少的嵌入式设备,这么操作可以达到节约内存消耗,提高程序运行效率的目的。
Demo示例
demo核心知识点:通过位运算符(布尔位运算符:"~"、"&"、"|";移位运算符:"<<")实现int数与多枚举值互转。

Code:

#include using namespace std; int nFlag = 0; //用移位表示各个枚举的开关typedef enum{TYPEA, //A开启,则nflag为1=0x00000001TYPEB, //B开启,则nflag为2=0x00000010TYPEC, //C开启,则nflag为4=0x00000100TYPED, //D开启,则nflag为8=0x00001000TYPENUM //枚举最大值,计数用}EMTypeNum; void int2enum (int n){if(n&(0x01<
Result:
nFlag:1
TYPEA is ON
TYPEB is OFF
TYPEC is OFF
TYPED is OFF
nFlag:3
TYPEA is ON
TYPEB is ON
TYPEC is OFF
TYPED is OFF
nFlag:7
TYPEA is ON
TYPEB is ON
TYPEC is ON
TYPED is OFF
nFlag:15
TYPEA is ON
TYPEB is ON
TYPEC is ON
TYPED is ON
nFlag:14
TYPEA is OFF
TYPEB is ON
TYPEC is ON
TYPED is ON
【C/C++|C/C++ int数与多枚举值互转的实现】nFlag:12
TYPEA is OFF
TYPEB is OFF
TYPEC is ON
TYPED is ON
nFlag:8
TYPEA is OFF
TYPEB is OFF
TYPEC is OFF
TYPED is ON
nFlag:0
TYPEA is OFF
TYPEB is OFF
TYPEC is OFF
TYPED is OFF
到此这篇关于C/C++ int数与多枚举值互转的实现的文章就介绍到这了,更多相关C++ int数与多枚举值互转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读