简体   繁体   中英

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. 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".

You pretty much have it, except that you need to initialize the bitfield to 0 as you add in more bits:

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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