What does typedef enum syntax like '1 << 0' mean?
This question already has an answer here:
This is common to the C-family of languages, and works identically in C, C++, and Objective-C. Unlike Java, Pascal, and similar languages, a C enum is not limited to the values named for it; it actually is an integral type of a size that can represent all the named values, and one can set a variable of the enum type to an arithmetic expression in the enum members. Typically, one uses bit shifts to make the values powers of 2, and one uses bit-wise logical operations to combine values.
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0 // 1
} permission; // A miniature version of UNIX file-permission masks
Again, the bit-shift operations are all from C.
You can now write:
permission all = read | write | execute;
You could even include that line in the permission declaration itself:
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0, // 1
all = read | write | execute // 7
} permission; // Version 2
How do you turn execute
on for a file?
filePermission |= execute;
Note that this is dangerous:
filePermission += execute;
This will change something with value all
to 8
, which makes no sense.
<<
is called the left shift operator.
http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_Left_Shift
Long story short 1 << 0 = 1
, 1 << 1 = 2
, 1 << 2 = 4
and 1 << 3 = 8
.
It looks like the typedef
is representing a bit field value. 1 << n
is 1
shifted left n
bits. So each enum
item represents a different bit setting. That particular bit set or clear would indicate something being one of two states. 1
shifted left by zero bits is 1
.
If a datum is declared:
CMAttitudeReferenceFrame foo;
Then you can check any one of four independent states using the enum
values, and foo
is no bigger than an int
. For example:
if ( foo & CMAttitudeReferenceFrameXArbitraryCorrectedZVertical ) {
// Do something here if this state is set
}
链接地址: http://www.djcxy.com/p/12568.html
上一篇: 为什么1 << 3等于8而不是6?