Spa*_*Dog 1 c cocoa cocoa-touch objective-c ios
我不是C/C++的专家.
我今天发现了这个宣言:
typedef NS_OPTIONS(NSUInteger, PKRevealControllerType)
{
PKRevealControllerTypeNone = 0,
PKRevealControllerTypeLeft = 1 << 0,
PKRevealControllerTypeRight = 1 << 1,
PKRevealControllerTypeBoth = (PKRevealControllerTypeLeft | PKRevealControllerTypeRight)
};
Run Code Online (Sandbox Code Playgroud)
你们能翻译每个价值会有什么价值吗?
opertor <<是 按位左移运算符.将所有位移到指定的次数:(算术左移和保留符号位)
m << n
Run Code Online (Sandbox Code Playgroud)
将所有位m向左移位n多次.(注意一个班次==乘以2).
1 << 0意味着没有转变所以1它只等于.
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
Run Code Online (Sandbox Code Playgroud)
虽然1 << 0它只是图1之一.(注意第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
Run Code Online (Sandbox Code Playgroud)
|是有点明智的运营商.在下面的代码中它or 1 | 2==3
PKRevealControllerTypeNone = 0, // is Zero
PKRevealControllerTypeLeft = 1 << 0, // one
PKRevealControllerTypeRight = 1 << 1, // two
PKRevealControllerTypeBoth = (PKRevealControllerTypeLeft |
PKRevealControllerTypeRight) // three
Run Code Online (Sandbox Code Playgroud)
没有更多的技术理由来初始化像这样的值,这样的定义可以很好地解读这个答案:定义SOMETHING(1 << 0)
编译器优化将它们转换为更简单的类似:( 我不确定第三个,但我认为编译器也会优化它)
PKRevealControllerTypeNone = 0, // is Zero
PKRevealControllerTypeLeft = 1, // one
PKRevealControllerTypeRight = 2, // two
PKRevealControllerTypeBoth = 3, // Three
Run Code Online (Sandbox Code Playgroud)
编辑: @thanks to Till.阅读此答案带有BOOL标志的应用程序状态显示了使用位运算符获得的声明的有用性.