简体   繁体   English

如何动态组成位掩码?

[英]How to dynamically compose a bitmask?

Lets say I have to provide an value as bitmask. 可以说我必须提供一个值作为位掩码。

NSUInteger options = kFoo | kBar | kFooBar;

and lets say that bitmask is really huge and may have 100 options. 并说位掩码确实很大,可能有100个选项。 But which options I have, depends on a lot of situations. 但是我有哪些选择取决于很多情况。 How could I dynamically compose such a bitmask? 我如何动态组成这样的位掩码?

Is this valid? 这有效吗?

NSUInteger options;

if (foo) {
    options = options | kFoo;
}

if (bar) {
    options = options | kBar;
}

if (fooBar) {
    options = options | kFooBar;
}

(despite the fact that this would probably crash when doing that | bitmask operator thing to "nothing". (尽管在执行| bitmask运算符操作为“无”时这可能会崩溃。

You pretty much have it, except that you need to initialize the bitfield to 0 as you add in more bits: 除了添加更多位时需要将位字段初始化为0以外,几乎所有其他功能都可以使用:

NSUInteger options = 0;

if (foo) options |= kFoo;
if (bar) options |= kBar;
// etc.

Also note that a bitfield can only hold a limited number of bits (typically 32 or 64 bits). 还要注意,位域只能容纳有限数量的位(通常为32或64位)。 If you need more bits (such as the 100 you mentioned), then you need an array of integers, and you need to take special care when setting and getting bits to access the right array element and the right bit of that element. 如果需要更多位(例如您提到的100),则需要一个整数数组,并且在设置和获取位以访问正确的数组元素和该元素的正确位时需要特别小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM