了解按位运算符并比较它们
Understand about bitwise operator and comparing them
总结(想要tl;dr版本的可以跳到下面的问题):
我刚遇到这个问题:Comparing UIDeviceOrienation and UIInterfaceOrientation。之后,我看了看按位是如何工作的(因为我有时见过它们,但不是很了解它们是如何工作的。)
所以,我研究了 What's bitwise operator, How enum in objective-c work with bit, How to use enum that's in bit。
(TL;DR) 现在,我的问题是:
比方说,我想检查我的 UIInterfaceOrientation = Landscape (Left | Right) 是否应该像这样使用它:
[UIApplication sharedApplication].statusBarOrientation ==
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
或
[UIApplication sharedApplication].statusBarOrientation &
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
他们应该给出相同的结果吗?还是不同?哪个更合适?
(以我简单的想法,如果没有错那么第二个更合适)。
奖金问题
除了枚举,还有什么地方可以有效地使用按位、位移运算符吗?
这取决于你想做什么:
第一个方法意味着:
已设置 UIInterfaceOrientationLandscapeLeft AND UIInterfaceOrientationLandscapeRight,但未设置其他选项(即使语义不同)。
这永远不会成立,因为 UIInterfaceOrientationLandscapeLeft 和 UIInterfaceOrientationLandscapeRight 是互斥的。
第二种方法意味着:
已设置 UIInterfaceOrientationLandscapeLeft 或 UIInterfaceOrientationLandscapeRight 并忽略其他选项。
这可能就是您想要做的。
但是你真的应该阅读一些关于位操作的知识。网上有大量的教程。您也可以使用所有与 C 打交道的教程。
奖金问题:
一个。我得到的奖金是多少?
b。是的,您不需要 enum
来声明常量。您可以简单地使用全局常量来做到这一点:
const int Option1 = 1 << 0;
const int Option2 = 1 << 1;
…
c。除此之外,你还可以用位运算做一些算术魔术,比如除以和乘以 2 的幂,检查数字是偶数还是奇数,...
总结(想要tl;dr版本的可以跳到下面的问题):
我刚遇到这个问题:Comparing UIDeviceOrienation and UIInterfaceOrientation。之后,我看了看按位是如何工作的(因为我有时见过它们,但不是很了解它们是如何工作的。)
所以,我研究了 What's bitwise operator, How enum in objective-c work with bit, How to use enum that's in bit。
(TL;DR) 现在,我的问题是:
比方说,我想检查我的 UIInterfaceOrientation = Landscape (Left | Right) 是否应该像这样使用它:
[UIApplication sharedApplication].statusBarOrientation ==
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
或
[UIApplication sharedApplication].statusBarOrientation &
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
他们应该给出相同的结果吗?还是不同?哪个更合适?
(以我简单的想法,如果没有错那么第二个更合适)。
奖金问题
除了枚举,还有什么地方可以有效地使用按位、位移运算符吗?
这取决于你想做什么:
第一个方法意味着:
已设置 UIInterfaceOrientationLandscapeLeft AND UIInterfaceOrientationLandscapeRight,但未设置其他选项(即使语义不同)。
这永远不会成立,因为 UIInterfaceOrientationLandscapeLeft 和 UIInterfaceOrientationLandscapeRight 是互斥的。
第二种方法意味着:
已设置 UIInterfaceOrientationLandscapeLeft 或 UIInterfaceOrientationLandscapeRight 并忽略其他选项。
这可能就是您想要做的。
但是你真的应该阅读一些关于位操作的知识。网上有大量的教程。您也可以使用所有与 C 打交道的教程。
奖金问题:
一个。我得到的奖金是多少?
b。是的,您不需要 enum
来声明常量。您可以简单地使用全局常量来做到这一点:
const int Option1 = 1 << 0;
const int Option2 = 1 << 1;
…
c。除此之外,你还可以用位运算做一些算术魔术,比如除以和乘以 2 的幂,检查数字是偶数还是奇数,...