枚举中的位运算学习笔记

我们经常遇到,系统定义的枚举中,经常遇到位运算。就像下面代码块中所用到的那样(<<),位运算是怎么运算的呢?它究竟有什么作用呢?

枚举与位运算学习Demo链接

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
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值