typedef enum 语法中的 '1 << 0' 是什么意思?

38 浏览
0 Comments

typedef enum 语法中的 '1 << 0' 是什么意思?

这个问题已经有了答案什么是位移(bit-shift)运算符,它们怎么工作?

我有点熟悉C和C++的typedef enum语法。现在我正在编写Objective-C程序,遇到了以下示例中的语法。我不确定这个语法是Objective-C特有的还是普遍适用的。但是,我的问题是在下面的代码片段中,像1 << 0这样的语法是什么意思?

typedef enum {
   CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0,
   CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1,
   CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2,
   CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3
} CMAttitudeReferenceFrame;

admin 更改状态以发布 2023年5月21日
0
0 Comments

<<被称为左移操作符。

http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_Left_Shift

长话短说,1 << 0 = 11 << 1 = 21 << 2 = 4以及1 << 3 = 8

0
0 Comments

这是 C 语言家族中共同的特性,在 C、C++ 和 Objective-C 中的使用方式是相同的。 与 Java,Pascal 和类似语言不同,C 中的枚举不仅限于命名的值; 它实际上是一个能够表示所有命名值的大小的整数类型,可以将枚举类型的变量设置为枚举成员中的算术表达式。 通常,使用位移操作使值成为 2 的幂,使用位逻辑运算符组合值。

typedef enum {
   read    = 1 << 2,  // 4
   write   = 1 << 1,  // 2
   execute = 1 << 0   // 1
} permission;  // A miniature version of UNIX file-permission masks

同样,所有位移操作都来自于 C。

现在您可以编写以下内容:

permission all = read | write | execute;

您甚至可以将该行包含在权限声明本身中:

typedef enum {
   read    = 1 << 2,  // 4
   write   = 1 << 1,  // 2
   execute = 1 << 0,  // 1
   all     = read | write | execute // 7
} permission;  // Version 2

如何为文件打开“execute”?

filePermission |= execute;

请注意,这很危险:

filePermission += execute;

这将更改某个值为“全部”的东西为“8”,这是没有意义的。

0