Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does it mean by type = 1 << 0? [duplicate]

Tags:

c

objective-c

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.

like image 932
Calios Avatar asked Jun 07 '13 07:06

Calios


4 Answers

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

like image 88
Hanky Panky Avatar answered Oct 18 '22 16:10

Hanky Panky


<< is binary operator

1 << 0 = 1
1 << 1 = 2
1 << 2 = 4
like image 43
SiMet Avatar answered Oct 18 '22 16:10

SiMet


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
like image 33
Herm Avatar answered Oct 18 '22 16:10

Herm


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.

like image 28
Stas Avatar answered Oct 18 '22 14:10

Stas