【问题标题】:What does typedef enum syntax like '1 << 0' mean? [duplicate]typedef enum 语法如 '1 << 0' 是什么意思? [复制]
【发布时间】:2013-07-27 10:43:59
【问题描述】:

我对 C 和 C++ 的 typedef 枚举语法有点熟悉。我现在正在使用 Objective-C 进行编程,并遇到了以下示例中的语法。我不确定语法是否特定于 Objective-C。但是,我的问题是在下面的代码 sn-p 中,1 &lt;&lt; 0 这样的语法是什么意思?

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

【问题讨论】:

  • 感谢卡尔的帖子。仅供参考,我在发布之前进行了搜索。但我不知道这叫位移。
  • 没问题,这就是我们来这里的目的。 =)
  • 你的问题在这里回答:define SOMETHING (1 &lt;&lt; 0) 和理解&lt;&lt; 操作员vies this
  • 我看到有人将我的问题标记为重复。在发布我的问题之前,我查看了题为 Absolute Beginner's Guide to Bit Shifting 的文章。我的问题不是重复的,因为我指定我的问题是针对 Objective-C 的。虽然我知道 Objective-C 是从 C 派生的,但 Apple 可能会在 Objective-C 中添加一些额外的位移功能。因此,我提出了针对 Objective-C 的问题。

标签: objective-c c syntax enums typedef


【解决方案1】:

这在 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;

这会将值 all 的内容更改为 8,这没有任何意义。

【讨论】:

  • +1 迄今为止最好的答案。
  • 很好的答案。非常简洁明了。谢谢!!
【解决方案2】:

&lt;&lt; 称为左移运算符。

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

长话短说1 &lt;&lt; 0 = 11 &lt;&lt; 1 = 21 &lt;&lt; 2 = 41 &lt;&lt; 3 = 8

【讨论】:

    【解决方案3】:

    看起来typedef 代表一个位字段值。 1 &lt;&lt; n1 左移 n 位。所以每个enum 项目代表一个不同的位设置。该特定位设置或清除将指示某事是两种状态之一。 1左移零位是1

    如果声明了一个数据:

    CMAttitudeReferenceFrame foo;
    

    然后您可以使用enum 值检查四个独立状态中的任何一个,并且foo 不大于int。例如:

    if ( foo & CMAttitudeReferenceFrameXArbitraryCorrectedZVertical ) {
        // Do something here if this state is set
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多