everyone. When learning OC recently, I always come across enum like this.
enum {
type1 = 0,
type2 = 1 << 0,
type3 = 1 << 1,
};
What does it mean by type = 1 << 0 ? What is it usually used for? Thanks in forward.
Bitwise Shift Left Operator
In Objective-C the bitwise left shift operator is represented by the '<<' sequence, followed by the number of bit positions to be shifted
Source
Also read this famous post to understand what it does and how
<< is binary operator
1 << 0 = 1
1 << 1 = 2
1 << 2 = 4
This operator is a bitwise shift (not only in objective-c).
you can assign every entry in an enum an integervalue, so it is the same as
enum {
type1 = 0,
type2 = 1,
type3 = 2
};
you can use the shift-operator to easily assure that your enum entries can be bitwise added like
int bitmask = type2 | type3 //bitmask = 3
It is one bit shift. Such a construction could be used if you need to assign several types to something. It's called bit mask. Example:
enum {
type1 = 1,
type2 = 1 << 1,
type3 = 1 << 2,
};
Means that type1 is binary 00000001, type2 is 00000010, type3 is 00000100 and so on. So, if type mask is 3 (00000011) you know that your object is type1 and type2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With