我们经常遇到,系统定义的枚举中,经常遇到位运算。就像下面代码块中所用到的那样(<<),位运算是怎么运算的呢?它究竟有什么作用呢?
typedef NS_OPTIONS(NSUInteger, UIViewAnimationOptions) {
UIViewAnimationOptionLayoutSubviews = 1 << 0,
UIViewAnimationOptionAllowUserInteraction = 1 << 1, // turn on user interaction while animating
UIViewAnimationOptionBeginFromCurrentState = 1 << 2, // start all views from current value, not initial value
UIViewAnimationOptionRepeat = 1 << 3, // repeat animation indefinitely
} NS_ENUM_AVAILABLE_IOS(4_0);
我们在写枚举参数时,可以用 | 运算符传入多个枚举值,比如:UIViewAnimationOptionRepeat | UIViewAnimationOptionBeginFromCurrentState。之所以可以这样写,是因为在定义枚举时提供了位运算。我们通过一个Demo来看下其实现方法
typedef enum : NSUInteger{
/*
first : 0 0 0 0 0 0 0 1 : 1 * 2^0 = 1
second : 0 0 0 0 0 0 1 0 : 1 * 2^1 = 2
third : 0 0 0 0 0 1 0 0 : 1 * 2^2 = 4
*/
first = 1 << 0, // 1 * 2^0 = 1
second = 1 << 1, // 1 * 2^1 = 2
third = 1 << 2 // 1 * 2^2 = 4
} myEnum;
- (void)viewDidLoad {
[super viewDidLoad];
// 1,2,4
NSLog(@"%d,%d,%d",first,second,third);
[self test: first | second];
}
- (void)test:(NSInteger)count
{
// 1 2 0
NSLog(@"%d,%d,%d",count & first,count & second,count & third);
if (count & first) {
NSLog(@"first");
}
if (count & second) {
NSLog(@"second");
}
if (count & third) {
NSLog(@"third");
}
}
位运算
将一个数字转换成二进制数,枚举中使用的是1,所以二进制数就是 0000 0001 ,将其转换成十进制数就是 1 * 2^0 + 0 * 2 ^ 1 + 0 * 2 ^ 2 + …… ,实际上就是 2^0 。
而位运算 1 << 1,就是 0000 0010 ,将1向左移动1位,其结果就是 0 * 2^0 + 1 * 2^1 +……,结果是2 。同理,其它几个结果也是这么运算的
判断 | 运算符都传入了哪些值
如上面的Demo所示,通过&运算符,即可判断 | 运算符都传入了哪些值
count & first // 判断是否传入了first,如果传入了,值为1,否则为0
count & second // 判断是否传入了second,如果传入了,值为2,否则为0
count & third // 判断是否传入了third,如果传入了,值为4,否则为0