⭐C/C++の深入浅出⭐int数与多枚举值互转

Posted 谁吃薄荷糖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了⭐C/C++の深入浅出⭐int数与多枚举值互转相关的知识,希望对你有一定的参考价值。

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 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

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

结束寄语

有关int数与多枚举值互转的介绍就到此结束啦!下篇博文与各位再见面~

写博不易,如蒙厚爱,赏个关注,一键三连~~点赞+评论+收藏🤞🤞🤞,感谢您的支持~~

以上是关于⭐C/C++の深入浅出⭐int数与多枚举值互转的主要内容,如果未能解决你的问题,请参考以下文章

vue checkbox 布尔值互转01

kafka Consumer分区数与多线程消费topic

Android 下枚举型使用及与 int 转换的困惑

golang 基础 —— 字符串 与 int int64 互转

golang 基础 —— 字符串 与 int int64 互转

String int Integer之间互转