views:

138

answers:

1

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

+2  A: 

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.

Adam Rosenfield
At that point you'll want to use bit indices rather than mask values, because mask values are limited to the typical 32 or 64 bits just as well. Or split things up into several bitfields - surely those 100 options can be divided into categories?
Pieter Witvoet