C/C++ int数与多枚举值互转的实现
在C/C++在C/C++的开发中经常会遇到各种数据类型互转的情况,正常的互转有:单个枚举转int数,int数转float数,float数转double数等。但是我们有时也会遇到多个枚举值与数字互转的情形(例如多个算法类型枚举开启标志转成数字,这个数字来表示多个标志位,按位来表示)。这样一个数字就能表示很多个标志位了,针对内存较少的嵌入式设备,这么操作可以达到节约内存消耗,提高程序运行效率的目的。
Demo示例
demo核心知识点:通过位运算符(布尔位运算符:"~"、"&"、"|";移位运算符:"<<")实现int数与多枚举值互转。
Code:
#include <iostream> using namespace std; int nFlag = 0; //用移位表示各个枚举的开关 typedef enum { TYPEA, //A开启,则nflag为1=0x00000001 TYPEB, //B开启,则nflag为2=0x00000010 TYPEC, //C开启,则nflag为4=0x00000100 TYPED, //D开启,则nflag为8=0x00001000 TYPENUM //枚举最大值,计数用 }EMTypeNum; void int2enum (int n) { if(n&(0x01<<TYPEA)) { //为真 cout << "TYPEA is ON\n"; } else { //为假 cout << "TYPEA is OFF\n"; } if(n&(0x01<<TYPEB)) { //为真 cout << "TYPEB is ON\n"; } else { //为假 cout << "TYPEB is OFF\n"; } if(n&(0x01<<TYPEC)) { //为真 cout << "TYPEC is ON\n"; } else { //为假 cout << "TYPEC is OFF\n"; } if(n&(0x01<<TYPED)) { //为真 cout << "TYPED is ON\n"; } else { //为假 cout << "TYPED is OFF\n"; } } void enum2int(EMTypeNum eMType, bool bOn) { if(bOn) { nFlag |= (0x01 << eMType); } else { nFlag &= ~(0x01 << eMType); } cout << "nFlag:" << nFlag << endl; } int main() { int i = 0; for(i = 0; i < TYPENUM;i++) { enum2int((EMTypeNum)i, true); int2enum(nFlag); cout << endl; } for(i = 0; i < TYPENUM;i++) { enum2int((EMTypeNum)i, false); int2enum(nFlag); cout << endl; } return 0; }
Result:
nFlag:1
TYPEA is ON
TYPEB is OFF
TYPEC is OFF
TYPED is OFFnFlag:3
TYPEA is ON
TYPEB is ON
TYPEC is OFF
TYPED is OFFnFlag:7
TYPEA is ON
TYPEB is ON
TYPEC is ON
TYPED is OFFnFlag:15
TYPEA is ON
TYPEB is ON
TYPEC is ON
TYPED is ONnFlag:14
TYPEA is OFF
TYPEB is ON
TYPEC is ON
TYPED is ONnFlag:12
TYPEA is OFF
TYPEB is OFF
TYPEC is ON
TYPED is ONnFlag:8
TYPEA is OFF
TYPEB is OFF
TYPEC is OFF
TYPED is ONnFlag:0
TYPEA is OFF
TYPEB is OFF
TYPEC is OFF
TYPED is OFF