【问题标题】:Understand about bitwise operator and comparing them了解按位运算符并进行比较
【发布时间】:2015-09-18 10:31:03
【问题描述】:

总结(想要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)

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

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

(在我的简单想法中,如果没有错,那么第二个更合适)。

额外问题

除了枚举,还有什么地方可以有效地使用按位移位运算符吗?

【问题讨论】:

    标签: objective-c enums comparison bitwise-operators


    【解决方案1】:

    这取决于你想做什么:

    第一方法意味着:

    UIInterfaceOrientationLandscapeLeft 和 UIInterfaceOrientationLandscapeRight 已设置,并且未设置其他选项(即使具有不同的语义)。

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

    第二种方法意味着:

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

    这可能就是你想要做的。

    但是你真的应该读一些关于位操作的东西。网络上有大量的教程。您也可以使用所有处理 C 的教程。

    奖金问题:

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

    b.是的,您不需要 enum 来声明常量。您可以使用全局常量简单地做到这一点:

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

    c。除此之外,您还可以使用位运算来做一些算术魔术,例如除法和乘以 2 的幂,检查一个数字是偶数还是奇数,......

    【讨论】:

    • Bonus Q.a:你得到了我的一票 :))谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多