This is a way to create constants that are easy to mix. For example, you may have an API for ordering ice cream, and you can choose any of the vanilla, chocolate, and strawberry flavors. You can use booleans, but this is a bit heavy:
- (void) iceCreamWithVanilla: (BOOL) v chocolate: (BOOL) ch strawerry: (BOOL) st;
A good trick to solve this problem is to use numbers, where you can mix flavors with a simple add. Let's say 1 for vanilla, 2 for chocolate and 4 for strawberries:
- (void) iceCreamWithFlavours: (NSUInteger) flavours;
Now, if the number has its rightmost bit, its vanilla flavor in it, the other bit is chocolate, and the third bit on the right is strawberry. For example, vanilla + chocolate will be 1 + 2 = 3 decimal ( 011 in binary format).
The bit rate operator x << y takes the left number ( x ) and shifts its bits y times. This is a good tool for creating numerical constants:
1 << 0 = 001 // vanilla 1 << 1 = 010 // chocolate 1 << 2 = 100 // strawberry
Voila! Now that you need a view with a flexible left margin and a flexible right margin, you can mix flags using bitwise or: FlexibleRightMargin | FlexibleLeftMargin FlexibleRightMargin | FlexibleLeftMargin → 1<<2 | 1<<0 1<<2 | 1<<0 → 100 | 001 100 | 001 → 101 . On the receiving side, a method can mask an interesting bit using a logical and:
// 101 & 100 = 100 or 4 decimal, which boolifies as YES BOOL flexiRight = givenNumber & FlexibleRightMargin;
Hope this helps.
source share