简体   繁体   中英

Objective - C - Usage of << in enumeration

I can see in Apple's documentation that enumerations are sometimes defined like this

enum {
UICollectionViewScrollPositionTop = 1 << 0,
UICollectionViewScrollPositionBottom = 1 << 1
}

What does the << mean?

It's the bitwise shift left operator. It's used to create values having a single bit set, very common when combination through bitwise OR is intended.

For those values, you might later say:

const int top_and_bottom = UICollectionViewScrollPositionTop | UICollectionViewScrollPositionBottom;

which would result in top_and_bottom being set to 3 (binary 11 2 ).

<< stands for left shift.

It shifts the binary to specified bits, as 4<<1 will be 8 and 4<<2 will be 16 . Each left shift makes the value multiplied by 2.

1<<0 will be 1 while 1<<1 will be 2.

Check here

Here it is simply left bit shift. So this means 1<<0 = 1 for instance. And 1<<1 is two. Maybe the author chose this way to initialize the enumeration to emphasize on the fact that UICollectionViewScrollPositionTop has only the least significant bit on and UICollectionViewScrollPositionBottom has only the second to least significant bit on. I guess the usage for this enumeration is to somehow later form bitmasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM