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

时间:2021-07-27 08:57:21

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

Demo示例

demo核心知识点:通过位运算符(布尔位运算符:"~"、"&"、"|";移位运算符:"<<")实现int数与多枚举值互转。

Code:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#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

到此这篇关于C/C++ int数与多枚举值互转的实现的文章就介绍到这了,更多相关C++ int数与多枚举值互转内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/zcc1229936385/article/details/119889252