What does typedef enum syntax mean, like "1 << 0"?

I am a little familiar with the typedef enum syntax for C and C ++. Now I am programming in Objective-C and came across the syntax in the following example. I'm not sure if the Objective-C syntax is specific or not. But, my question is in the following code fragment, what does the syntax mean, for example 1 << 0 ?

 typedef enum { CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0, CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1, CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2, CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3 } CMAttitudeReferenceFrame; 
+6
source share
3 answers

This is common for the C-family of languages ​​and works identically in C, C ++ and Objective-C. Unlike Java, Pascal, and similar languages, the C listing is not limited to the values ​​given to it; it is actually an integral type of size that can represent all named values, and you can set an enumeration type variable to an arithmetic expression in enumeration members. As a rule, bit shifts are used so that the values ​​are 2, and bit-logical operations are used to combine the 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, bit shift operations are all from C.

Now you can write:

 permission all = read | write | execute; 

You can even include this 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 to enable execute for a file?

 filePermission |= execute; 

Please note that this is dangerous:

 filePermission += execute; 

This will change something with an all value of 8 , which makes no sense.

+10
source

<< is called the left shift operator.

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

In short, 1 << 0 = 1 , 1 << 1 = 2 , 1 << 2 = 4 and 1 << 3 = 8 .

+4
source

It seems that typedef represents the value of the bit field. 1 << n is 1 shifted left bit n . Therefore, each enum element represents a different bit setting. This particular bit or sharpness indicates that it is one of two states. 1 left shifted by zero bits 1 .

If an element name is declared:

 CMAttitudeReferenceFrame foo; 

You can then check any of the four independent states using enum values, and foo no more than int . For instance:

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

Source: https://habr.com/ru/post/950404/


All Articles