理解按位运算符并比较它们

时间:2015-09-18 10:31:03

标签: objective-c enums comparison bitwise-operators

摘要(对于想要tl; dr版本的人,您可以跳到下面的问题):

我刚刚解决了这个问题:Comparing UIDeviceOrienation and UIInterfaceOrientation。在那之后,我看了一下如何按位工作(因为我有时会看到它们,但不是真的了解它们是如何工作的。)

所以,我已经对What's bitwise operatorHow enum in objective-c work with bitHow to use enum that's in bit进行了研究。

(TL; DR)现在,我的问题在这里:

让我们说,我想检查我的UIInterfaceOrientation = Landscape(Left | Right)是否应该像这样使用它:

[UIApplication sharedApplication].statusBarOrientation ==
     (UIInterfaceOrientationLandscapeLeft |
      UIInterfaceOrientationLandscapeRight)

OR

[UIApplication sharedApplication].statusBarOrientation & 
    (UIInterfaceOrientationLandscapeLeft | 
     UIInterfaceOrientationLandscapeRight)

他们应该给出相同的结果吗?还是不同?哪一个更合适?

(简单来说,如果没有错,那么第二个更合适)。

奖金问题

除了枚举之外,还有其他地方我可以有效地使用bitwise,bitshift运算符吗?

1 个答案:

答案 0 :(得分:2)

这取决于你想做什么:

第一个方法意味着:

设置了UIInterfaceOrientationLandscapeLeft和UIInterfaceOrientationLandscapeRight,并且没有设置其他选项(即使使用不同的语义)。

这永远不会成立,因为UIInterfaceOrientationLandscapeLeft和UIInterfaceOrientationLandscapeRight是互斥的。

第二方法意味着:

UIInterfaceOrientationLandscapeLeft或UIInterfaceOrientationLandscapeRight已设置,其他选项将被忽略。

可能这就是你想要做的。

但你应该真正阅读有关位操作的内容。网上有大量的教程。您也可以使用每个处理C的教程。

奖金问:

一个。我得到的奖金是多少?

湾是的,您不需要enum来声明常量。你可以使用全局常量来做到这一点:

const int Option1 = 1 << 0;
const int Option2 = 1 << 1;
…

℃。除此之外,你可以通过位操作做一些算术魔术,比如用2的幂除法和乘法,检查数字是偶数还是奇数,......