Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "NSBinarySearchingFirstEqual = (1UL << 8)" mean in an enumeration definition?

I saw this in NSArray.h header file in the framework directory:

enum {
    NSBinarySearchingFirstEqual = (1UL << 8),
    NSBinarySearchingLastEqual = (1UL << 9),
    NSBinarySearchingInsertionIndex = (1UL << 10),
};
typedef NSUInteger NSBinarySearchingOptions;

What's the point of "NSBinarySearchingFirstEqual = (1UL << 8)"?And what's the relationship between this enumeration and the "NSBinarySearchingOptions" type-definition? Thanks.

like image 797
Li Fumin Avatar asked Jun 04 '10 03:06

Li Fumin


2 Answers

The "NSBinarySearchingFirstEqual = (1UL << 8)" etc. assign specific values to the enumeration constants. The values are chosen so that they are represented by a single bit, allowing the options to be combined with bitwise operations. The "<<" operator is a left shift; you could equivalently write this as:

enum {
    NSBinarySearchingFirstEqual = 256,
    NSBinarySearchingLastEqual = 512,
    NSBinarySearchingInsertionIndex = 1024,
};

Options can be combined like:

NSBinarySearchingOptions opt = NSBinarySearchingFirstEqual | NSBinarySearchingLastEqual;

Note that NSBinarySearchingOptions is typedef'd to an unsigned integer, not the enum, because it can contain values that are not one of the defined enum values (when multiple values are combined).

like image 164
David Gelhar Avatar answered Oct 16 '22 07:10

David Gelhar


Usually that sort of enum definition indicates it is a bit mask. Each member of the enumeration has a unique value but also only has one bit set, meaning that when you combine multiple values, you are still able to determine which ones were provided just by looking at which bits are set.

For example, assume this 32-bit integer represented in binary:

0000 0000 0000 0000 0000 0001 0000 0000

The 8th bit is set, which corresponds to the enum value NSBinarySearchingFirstEqual, since the value 1 shifted 8 bits to the left ends up being the 8th bit (assuming you order your bits from 0)

0000 0000 0000 0000 0000 0101 0000 0000

This previous 32-bit integer has 2 bits that are set, the 8th and the 10th. These two bits correspond to NSBinarySearchingFirstEqual and NSBinarySearchingInsertionIndex.

If you're unfamiliar with bit shifting, have a look at the Wikipedia article which has some useful diagrams.

The type definition means that an NSBinarySearchingOption is of type NSUInteger. Essentially they are the same thing, but by defining a different type it becomes clearer about what kind of values to provide to a method that takes an argument of this type.

like image 22
dreamlax Avatar answered Oct 16 '22 06:10

dreamlax