运算符<<
是 按位左移运算符。将所有位左移指定次数:(算术左移并保留符号位)
m << n
将 的所有位m
向左移动n
多次。(注意一班 == 乘以二)。
1 << 0
表示没有移位,因此它等于1
only。
1 << 1
表示一个班次,因此它仅等于1*2
= 2。
我用一个字节解释:一个字节是这样的:
MSB
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 / 0
| / 1 << 1
| |
▼ ▼
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
而1 << 0
除了图一之外什么也不做。(注意第 7 位被复制以保留符号)
OR 运算符:按位或
MSB PKRevealControllerTypeLeft
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | == 1
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
| | | | | | | | OR
MSB PKRevealControllerTypeRight
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | == 2
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
=
MSB PKRevealControllerTypeBoth
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | == 3
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
|
是位操作符。在下面的代码中它or
1 | 2
==3
PKRevealControllerTypeNone = 0, // is Zero
PKRevealControllerTypeLeft = 1 << 0, // one
PKRevealControllerTypeRight = 1 << 1, // two
PKRevealControllerTypeBoth = (PKRevealControllerTypeLeft |
PKRevealControllerTypeRight) // three
没有更多的技术原因来初始化这样的值,这样定义会使事情很好地排列起来阅读这个答案:define SOMETHING (1 << 0)
编译器优化将它们转换为更简单的:(我不确定第三个,但我认为编译器也会优化它)
PKRevealControllerTypeNone = 0, // is Zero
PKRevealControllerTypeLeft = 1, // one
PKRevealControllerTypeRight = 2, // two
PKRevealControllerTypeBoth = 3, // Three
编辑: @感谢直到。阅读此答案带有 BOOL 标志的 App States显示了使用位运算符获得的声明的有用性。