如何在C++中优雅地处理位掩码

How can I treat bit mask graceful in C++?

本文关键字:处理 掩码 C++      更新时间:2023-10-16

我遇到过这样的代码。

#define JOB_STATUS_PAUSED               0x00000001
#define JOB_STATUS_ERROR                0x00000002
#define JOB_STATUS_DELETING             0x00000004
#define JOB_STATUS_SPOOLING             0x00000008
#define JOB_STATUS_PRINTING             0x00000010
#define JOB_STATUS_OFFLINE              0x00000020
#define JOB_STATUS_PAPEROUT             0x00000040
#define JOB_STATUS_PRINTED              0x00000080
#define JOB_STATUS_DELETED              0x00000100
#define JOB_STATUS_BLOCKED_DEVQ         0x00000200
#define JOB_STATUS_USER_INTERVENTION    0x00000400
#define JOB_STATUS_RESTART              0x00000800
DWORD func();

函数返回一个双字,它是这些位掩码的组合。我想测试返回值的状态。我这样写代码。

if(ret&JOB_STATUS_PAUSED)
string str="JOB_STATUS_PAUSED";
if(ret&JOB_STATUS_ERROR)
string str="JOB_STATUS_ERROR";

我想知道有没有一种优雅的方法来治疗口罩?我认为std::bitset是不够的,我还需要获取宏的字符串。我认为这个宏可以帮助,但我不知道如何使用它

#define str(a) #a
//if I input str(JOB_STATUS_PAUSED) then I can get "JOB_STATUS_PAUSED"
#define str(a) L#a
const wchar_t* statusStr[]{
str(JOB_STATUS_PAUSED),
str(JOB_STATUS_ERROR),
str(JOB_STATUS_DELETING),
str(JOB_STATUS_SPOOLING),
str(JOB_STATUS_PRINTING),
str(JOB_STATUS_OFFLINE),
str(JOB_STATUS_PAPEROUT),
str(JOB_STATUS_PRINTED),
str(JOB_STATUS_DELETED),
str(JOB_STATUS_BLOCKED_DEVQ),
str(JOB_STATUS_USER_INTERVENTION),
str(JOB_STATUS_RESTART)
};
int len = dimof1(statusStr);
std::vector<std::wstring> ret;
for (int i = 0, init = 1; i < len; i++) {
if (status & init) {
ret.push_back(statusStr[i]);
}
init = init << 1;
}
return ret;
#undef str

我认为这符合我的要求。