|= 和 &= 如何工作?
我想以这样一种方式进行枚举: 我可以简单地这样
做:
enum Things
{
Something,
SomethingElse
};
或者我必须小心地给他们特定的数字才能使其工作?
另外,如果一个值,比如 3,已经被 |= 写入,那么 |= 它会再次导致故障(如 if(attributes & 3) 将不再起作用)
谢谢
I want to make an enum in such a way that I can & parameters after |ing them in.
Can I simply do:
enum Things
{
Something,
SomethingElse
};
Or must I be careful to give them specific numbers for this to work?
Also if a value, like say, 3, has already been |='d in, would |= it in again cause this to malfunction (as in, if(attributes & 3) would no longer work)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
然后将您的枚举定义为:
这个想法是,二进制表示中只有一位应该是
1
,其他应该是0
,如上面的注释所示。另外,我在注释中仅使用了 8 位,这并不意味着枚举值是一个字节大小。我只是为了方便才使用它们。枚举值可以非常大,甚至可以容纳long
。Then define your enum as:
The idea is, only one bit in the binary representation should be
1
, others should be0
, as shown in the comments above. Also, I used 8 bits only in the comment, that doesn't mean that the enum values are one byte size. I only used them for convenience. Enum values can be very large, can hold evenlong
.您必须使用特殊值,即 2 的幂 (1, 2, 4, 8, 16, ...)。
在进一步研究这个“|和&功能”之前,你可能应该阅读这篇文章:
http://en.wikipedia.org/wiki/Binary_numeral_system
这也可能值得一读:< a href="http://en.wikipedia.org/wiki/Flag_(计算" rel="nofollow">http://en.wikipedia.org/wiki/Flag_(计算)
You have to use special values, namely powers of two (1, 2, 4, 8, 16, ...).
And you should probably read this before investigating this "| and & feature" any further:
http://en.wikipedia.org/wiki/Binary_numeral_system
This might also be worth reading: http://en.wikipedia.org/wiki/Flag_(computing)
当您利用计算机的本机二进制编码时,使用
|
和&
打包标志效果最佳。因此,使用 2 的幂(此处采用十进制表示形式):
这使得每个标志都可以唯一用整数的一位来表示,从而允许单独激活和停用每个标志。
结果是:
我希望这是有道理的。
Packing flags with
|
and&
works best when you take advantage of the computer's native binary encoding.So, using the powers of 2 (here in decimal representation):
This enables each flag to be represented exclusively in a single bit of an integer, allowing each one to be activated and de-activated individually.
The result is:
I hope that this makes sense.
如果要对 Enum 使用按位运算,则值必须是 2 的幂。这通常称为 位字段。
If you want to use bit-wise operations with an Enum, the values must be a power of 2. This is commonly referred to as a Bit Field.
您可以使其变得更容易:
正如纳瓦兹所说,如果您使用十六进制代码,或者甚至更好地使用宏,
As Nawaz said and you can make it easier if you use a hexadecimal codes
Or even better use a macro: