小编给大家分享一下C/C++中如何实现int数与多枚举值互转,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
在C/C++在C/C++的开发中经常会遇到各种数据类型互转的情况,正常的互转有:单个枚举转int数,int数转float数,float数转double数等。但是我们有时也会遇到多个枚举值与数字互转的情形(例如多个算法类型枚举开启标志转成数字,这个数字来表示多个标志位,按位来表示)。这样一个数字就能表示很多个标志位了,针对内存较少的嵌入式设备,这么操作可以达到节约内存消耗,提高程序运行效率的目的。
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; }
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
以上是“C/C++中如何实现int数与多枚举值互转”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。