在 C++ 中使用 #define 定义位标志
我正在学习位标志。我已经知道它们是如何工作的以及它们是如何在 struct
中定义的。但是,我不确定它们是否可以在 #define
预处理器指令中定义,如下所示:
#define FLAG_FAILED:1
Is this preprocessor Define Directive the as a struct
bit-flagDefinition?
PS:我已经遇到过这个相关问题,但它没有回答我的问题:#define 位标志和枚举 - 在“c”中和平共存。另外,如果您可以向我指出一些有关预处理器指令的信息,我将不胜感激。
I'm learning about bit-flags. I already know how they work and how they are defined in a struct
. However, I'm unsure if they can be defined in a #define
preprocessor directive like this:
#define FLAG_FAILED:1
Is this preprocessor define directive the as a struct
bit-flag definition?
PS: I've already come across this related question but it didn't answer my question: #defined bitflags and enums - peaceful coexistence in "c". Also, if you can point me towards some information regarding preprocessor directives, I would appreciate that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
任何您想要用来将位标志注入到结构中的 #define 都必须采用以下形式:
在您假定的用途中...
标识符包含冒号,这使其无效。
你可以做这样的事情:
目前还不清楚为什么你要考虑使用位字段的定义。如果您只是想改变字段长度,那么:
...或...
Any #define that you want to use to inject bitflags into a struct must take the form:
In your postulated use...
The identifier contains the colon, which makes it invalid.
You could do something like this:
It's not clear why you're considering using a define for the bit field anyway. If you just want to be able to vary the field length, then:
...or...
#define FLAG_FAILED:1
并不是大多数人所知道的“位标志”意义上的真正位标志。这也是糟糕的语法。通常定义位标志,以便您拥有一个类型,并通过“设置”它们来“打开”位。您可以通过“清除”标志来“关闭”它们。要比较位标志是否打开,您可以使用所谓的按位运算符
AND
(例如&)。因此,您的 BIT0(例如 2^0)将定义为
BIT0 = 0x00000001
,BIT1(例如 2^1)将定义为BIT1 = 0x00000002
。如果您想坚持使用定义,您可以通过设置和清除来实现:或者作为模板
如果您想设置位,可以这么说,您可以设置如下状态:
setBit(SystemState, SYSTEM_ONLINE);
或
setBit(SystemState,SYSTEM_ONLINE);
清除效果相同,只需替换
setBit
与clrBit
。要进行比较,只需执行以下操作:
如果这是在
struct
中,则引用该struct
。#define FLAG_FAILED:1
is not really a bit flag in the sense that what most people know as a "bit flag". It's also bad syntax.Bit flags typically are defined so that you have a type and you turn "on" bits by "setting" them. You turn them "off" by "clearing" the flag. To compare if the bit flag is on, you use what is called the bitwise operator
AND
(e.g. &).So your BIT0 (e.g. 2^0) would be defined as
BIT0 = 0x00000001
and BIT1 (e.g. 2^1) asBIT1 = 0x00000002
. If you wanted to stick with define you could do it this way with setting and clearing:or as a template
If you want to set the bit, so to speak, you could have a state set as follows:
setBit(SystemState, SYSTEM_ONLINE);
or
setBit(SystemState, <insert type here>SYSTEM_ONLINE);
clearing would be the same just replace
setBit
withclrBit
.To compare, just do this:
if this is in a
struct
then, reference thestruct
.使用 #define 宏定义按位值的形式是:
A form to define bitwise values with #define macros is: