What does this enum mean? - c

I saw this line of code today and had no idea what it does.
typedef enum {
SomeOptionKeys = 1 << 0 // ?
} SomeOption;
Some usage or example would be helpful. Thanks!

It looks like it defines an enumerated type that is supposed to contain a set of flags. You'd expect to see more of them defined, like this:
typedef enum {
FirstOption = 1 << 0,
SecondOption = 1 << 1,
ThirdOption = 1 << 2
} SomeOption;
Since they are defined as powers of two, each value corresponds to a single bit in an integer variable. Thus, you can use the bitwise operators to combine them and to test if they are set. This is a common pattern in C code.
You could write code like this that combines them:
SomeOption myOptions = FirstOption | ThirdOption;
And you could check which options are set like this:
if (myOptions & ThirdOption)
{
...
}

The value of SomeOptionKeys is one, this is a useful representation when working with flags:
typedef enum {
flag1 = 1 << 0, // binary 00000000000000000000000000000001
flag2 = 1 << 1, // binary 00000000000000000000000000000010
flag3 = 1 << 2, // binary 00000000000000000000000000000100
flag4 = 1 << 3, // binary 00000000000000000000000000001000
flag5 = 1 << 4, // binary 00000000000000000000000000010000
// ...
} SomeOption;
Whit way each flag has only one bit set, and they could be represented in a bitmap.
Edit:
Although, I have to say, that I might be missing something, but it seems redundent to me to use enums for that. Since you lose any advantage of enums in this configuration, you may as well use #define:
#define flag1 (1<<0)
#define flag2 (1<<1)
#define flag3 (1<<2)
#define flag4 (1<<3)
#define flag5 (1<<4)

It just sets the enum to the value 1. It is probably intended to indicate that the values are to be powers of 2. The next one would maybe be assigned 1 << 1, etc.

<< is the left shift operator. In general, this is used when you want your enums to mask a single bit. In this case, the shift doesn't actually do anything since it's 0, but you might see it pop up in more complex cases.
An example might look like:
typedef enum {
OptionKeyA = 1<<0,
OptionKeyB = 1<<1,
OptionKeyC = 1<<2,
} OptionKeys;
Then if you had some function that took an option key, you could use the enum as a bitmask to check if an option is set.
int ASet( OptionKeys x){
return (x & OptionKeyA);
}
Or if you had a flag bitmap and wanted to set one option:
myflags | OptionKeyB

Related

Using a bitmask and if statement

I am trying to allow multiple cases to run in a switch statement. I have a bitmask as follows:
#define SHOOT_ROCKET 2 << 16
#define MOVE_FORWARD 3 << 16
Later, I do
switch (int game_action)
and I have
case SHOOT_ROCKET:
result = fire_weapon(rl);
I don't want to 'break', because I want possibility of multiple actions. But I am returning a value called 'result'. I store this as a variable and return at the end. I can tell other case: statements are running though even when they shouldn't because result keeps getting changed and doesn't if I add break;
What is the best way to deal with this?
Update: I've been told to do if instead.
I changed my << bitmasks so they start at 1 now.
I am experiencing a weird bug
if (game_action->action & SHOOT_ROCKET)
{
game_action->data=5;
}
if (game_action->action & MOVE_FORWARD)
{
game_action->data=64;
}
I am not concerned about game_action being overwritten when I intend for multiple if's to evaluate to true
However: it seems MOVE_FORWARD is happening even if I only try and shoot a rocket!
game_action is a void pointer normally, so this is how it's setup in the function:
game_action = (game_action) *game_action_ptr;
I have verified the bitmask is correct with
printf("%d", game_action->action >> 16) which prints 2.
So why is '3' (the move forward) happening when I am only trying to shoot a rocket?
Please do update your question.
So why is '3' (the move forward) happening when I am only trying to shoot a rocket?
The first thing you want to look at is
#define SHOOT_ROCKET 2 << 16
#define MOVE_FORWARD 3 << 16
and think what that evaluates to. It will evaluate to the following binary numbers (Python is handy for this kind of stuff, 0b is just a prefix that means binary is following):
>>> bin(2 << 16)
'0b100000000000000000'
>>> bin(3 << 16)
'0b110000000000000000'
So you see that you use one bit twice in your #defines (Retired Ninja already pointed this out). This means that if game_action->action is set to anything where the bit 2 << 16 is 1, both of your ifs will evaluate to true, because both #defines have that bit set to 1.
to make them mutually exclusive, should i do 2, 4, 8, instead of 1,2,3,4?
If you want to easily keep track of which bits are used, you can either use powers of two (1,2,4,8,16, etc), e.g. #define MOVE_FORWARD 4 (I'm ignoring the << 16 you have, you can add that if you want), or you can shift a 1 by a variable number of bits, both result in the same binary numbers:
#define MOVE_LEFT 1 << 0
#define MOVE_RIGHT 1 << 1
#define MOVE_UP 1 << 3
#define MOVE_DOWN 1 << 4
There are legitimate cases where bitmasks need to have more than one bit set, for example for checking if any one of several bits are set:
#define MOVE_LEFT ... (as above)
#define SHOOT_ROCKET 1 << 5
#define SHOOT_GUN 1 << 6
//...
#define ANY_MOVEMENT 0xF
#define ANY_WEAPON_USE 0xF << 4
and then check:
if (action & ANY_MOVEMENT) { ... }
if (action & ANY_WEAPON_USE) { ... }
place parens '(' ')' around the value part (2<<15) kind of values so there is no errors introduced by the text replacement.
I.E. this:
'if( (&game_action->action & MOVE_FORWARD) == MOVE_FORWARD)'
becomes
'if( (&game_action->action & 2 << 16) == 2 << 16)'
Note the posted code is missing a left paren, which I added.
Where the '&' has a higher Precedence the '<<' so it (effectively) becomes
'if( ( (&game_action->action & 2) << 16) == 2 << 16)'
where the '&' is done to the 2 and not to the 2<<16

Why is this line obfuscated?

In this snippet,
if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
{
/* statements */
}
the member OscillatorType could have any of the values, or their combination, defined below.
#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000)
#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001)
#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002)
#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004)
#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008)
Why is the if written this way? Why not simply like this?
if(RCC_OscInitStruct->OscillatorType == RCC_OSCILLATORTYPE_HSI)
RCC_OscInitStruct->OscillatorType is a collection of bits packed in an integer value, each bit representing one of the values (RCC_OSCILLATORTYPE_HSE, ...). That's why they come in powers of 2. The code you showed just checks if the bit associated with RCC_OSCILLATORTYPE_HSI is set. It's very probable that bits of other values are also set.
For example if the binary representation of OscillatorType is 0...011, the first and second bit is set, meaning that the RCC_OSCILLATORTYPE_HSE and RCC_OSCILLATORTYPE_HSI values are selected.
It's a very common C idiom and not obfuscated in any way. Those are two very different tests.
if ((RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
says "if the RCC_OSCILLATOR_HSI bit is 1". It doesn't care whether any of the other bits are 0 or 1, whereas
if (RCC_OscInitStruct->OscillatorType == RCC_OSCILLATORTYPE_HSI)
says "if the RCC_OSCILLATOR_HSI bit is 1 AND all the other bits are 0".
Because it may have any of these values at the same time. The & (bitwise AND) operator is serving the purpose of extracting only the value RCC_OSCILLATOR_TYPE_HSI.
As an example, your input may look like this:
010011
While RCC_OSCILLATOR_TYPE_HSI looks like this:
000010
The AND operator with these two values will return 000010, witch exactly equals RCC_OSCILLATOR_TYPE_HSI.
However, if your input looks like this:
110101
The bitwise AND operator between this and RCC_OSCILLATOR_TYPE_HSI will return 0, and the condition will be false.
The if condition is interested only in the second last bit of RCC_OscInitStruct->OscillatorType. So RCC_OSCILLATORTYPE_HSI is used as a mask and then compared to itself.
If you see all the constants, first one is all zeroes where as the others have its set bit at successive positions.
Now, doing & with any of these constants can tell you whether its corresponding bit is set in the said parameter.
If you want to set all of the possible values, you would be doing:
RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI;
Why comparison using ==?
That's not required and makes the code cluttered. I think that the programmer wanted to bring uniformity when testing for RCC_OSCILLATORTYPE_NONE.
The programmer can't test for RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE_NONE because that would evaluate to zero. You are either forced to negate the condition just for this check.
An example:
#include <stdio.h>
#include <stdint.h>
#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000)
#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001)
#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002)
#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004)
#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008)
int main(void)
{
/* set HSI and HSE */
uint32_t flags = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI;
if (flags == RCC_OSCILLATORTYPE_HSI) {
puts("flags = HSI");
}
if ((flags & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) {
puts("HSI is set in flags");
}
return 0;
}
Output:
HSI is set in flags
To begin with, == is not equivalent with &. Because == looks at the whole 32 bit register, including any crap you aren't interested in. While & just looks at the relevant parts.
And the & is simple binary arithmetic for bitwise AND. In my opinion, you need to understand binary numbers before even enrolling your first programmer course, but maybe that's just me.
Anyway, given that you actually understand what bitwise AND does, it would have made more sense if you had code like
#define RCC_OSCILLATORTYPE ((uint32_t)0x0000000F) // mask
#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000)
#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001)
#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002)
#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004)
#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008)
...
(RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE) == RCC_OSCILLATORTYPE_HSI
Maybe this is what the programmer of that code intended, but they didn't quite manage to bring the code all the way there.

Store zeros from ints and use them later

I have 3 sensors that each provide either 0 or 1 (repeatedly in a loop). They are stored individually as int variables. These are then printed using the following:
print ("%d%d%d", Sensor1, Sensor2, Sensor3);
I want to store each combination (ex: 010, 001, 110, etc.) temporarily so that I can use it do something else (I want to have a switch or something eventually where I can do a different operation depending on the value of the sensor combination). I can't store it as an int since that drops the 0s in front.
How can I store these combinations?
You can use structure bit field for this.
struct Bit{
bool Sensor1 : 1;
bool Sensor2 : 1;
bool Sensor3 : 1;
};
int main(void)
{
struct Bit bit = {0, 1, 0};
printf ("%d%d%d", bit.Sensor1, bit.Sensor2, bit.Sensor3);
}
So you have
int Sensor1, Sensor2, Sensor3;
// have code to initialize above variables to 0 or 1
To store these as one integer in base 10, assuming they really all are 0 or 1, you can do:
int Sensors_10 = Sensor1 * 100 + Sensor2 * 10 + Sensor3;
And then to get them back:
Sensor1 = Sensors_10 / 100 % 10;
Sensor2 = Sensors_10 / 10 % 10;
Sensor3 = Sensors_10 % 10;
Obviously order of sensors can be whatever, as long as it matches between packing and unpacking.
But, you only need 1 bit to store each sensor, so could use binary:
int Sensors_2 = Sensor1 * 4 + Sensor2 * 2 + Sensor3;
...
Sensor1 = Sensors_2 / 4 % 2;
Sensor2 = Sensors_2 / 4 % 2;
Sensor3 = Sensors_2 % 2;
But, with computer binary numbers are special, so the binary version is more commonly written like this:
int Sensors_2 = Sensor1 << 2 | Sensor2 << 1 | Sensor3;
...
Sensor1 = Sensors_2 >> 2 & 1;
Sensor2 = Sensors_2 >> 1 & 1;
Sensor3 = Sensors_2 & 1;
Where |, <<, >> and & are bitwise OR, shift and AND operators, and explaining what they do is beyond scope of this question, but one note about them: When there are no "overlapping" one-bits and numbers are positive, then result of | is same as result of +.
Answer of haccks covers how to make C compiler do this for you, without doing your own bit manipulation.
To print Sensors_10 with leading zeros, you can do printf("%03d", Sensors_10);. C standard library does not have a way to print binary numbers directly, so you need your own code to print the bits one-by-one, so you might as well printf("%d%d%d", Sensor1, Sensor2, Sensor3); then.
You can use a 2D int array to store the values and use it later.
E.g int sen_value[1000][3]; use it in the loop to store the values.
Example how you can use it in loop:
#include <stdio.h>
int main ()
{
int i;
int sen_value[10][3];
for(i=0;i<10;i++)
{
//Assigning the values
sen_value[i][0] = 0;
sen_value[i][1] = 0;
sen_value[i][2] = 0;
//Use the way you want
printf("%d %d %d\n",sen_value[i][0],sen_value[i][1],sen_value[i][2]);
}
return 0;
}
Or you can use it just once and then reset it after each operation, For example:
#include <stdio.h>
int main ()
{
int sen_value[1][3];
//Assigning the values
sen_value[0][0] = 0;
sen_value[0][1] = 0;
sen_value[0][2] = 0;
//Use the way you want
printf("%d %d %d\n",sen_value[0][0],sen_value[0][1],sen_value[0][2]);
return 0;
}
If you are using a linux environment then by using the command you can easily save the output that are displayed in your console.
Let here sensor.c be your source file Then,
$ gcc -o a sensor.c
$ ./a > senser.txt
Then you have a .txt file with all output stored in a txt file. And these can be again used as inputs in your other.c files like :
$ gcc -o other other.c
$ ./other < senser.txt
If you want to store those sensor1,sensor2,sensor3 internally and use internally then you can simply use the arrays or Structure like :
main(){
int Sensor[1][3];
Sensor[0][0] = 0;
Sensor[0][1] = 1;
Sensor[0][2] = 0;
print ("%d%d%d", Sensor[0][0], Sensor[0][1], Sensor[0][2]);
}
While the leading zeroes of an integer are not displayed when printed, that does not mean they are "dropped"; they are merely implicit - that is a matter of the format specifier used in teh output of the value rather than the zeros not being present. An int is always a fixed number of binary digits.
Consider:
uint32_t sensor_state = (sensor3 << 3) | (sensor2 << 1) | sensor1 ;
Note that uint32_t is a type alias for an unsigned integer 32 bits in length. It is defined by including the <stdint.h> header file. In this case a plain int would work, but when you are dealing with data at the bit level it is good to be explicit (and unsigned). Here of course a uint8_t would work too, and if your target is an 8 bit device, I suggest you use that.
Here sensor_state is a binary combination of the three sensor values and will have one of the following values:
Sensors sensor_state
3 2 1 binary decimal hexadecimal
---------------------------------------
0 0 0 0000 0 0x00
0 0 1 0001 1 0x01
0 1 0 0010 2 0x02
0 1 1 0011 3 0x03
1 0 0 0100 4 0x04
1 0 1 0101 5 0x05
1 1 0 0110 6 0x06
1 1 1 0111 7 0x07
So you can switch on any combination:
switch( sensor_state )
{
case 0x00 :
...
break ;
case 0x01 :
...
break ;
case 0x02 :
...
break ;
...
case 0x07 :
...
break ;
default :
// unexpected invalid combination
break ;
}
You might usefully create an enumeration for each combination:
enum eSensorStates
{
NO_SENSOR = 0,
SENSOR1,
SENSOR2,
SENSOR12,
SENSOR3,
SENSOR13,
SENSOR23,
SENSOR123
}
Then you can write:
switch( sensor_state )
{
case NO_SENSOR :
...
break ;
case SENSOR1:
...
break ;
case SENSOR2:
...
break ;
...
case SENSOR123 :
...
break ;
default :
// unexpected invalid combination
break ;
}
You may of course use enumeration names that make specific sense in your application - that reflect the meaning or action for each combination rather than the generic names I have chosen.

How to Interpret typedef enum property on MCOIMAPMessage

My question is mostly about how interpret a typedef enum, but here is the background:
I am using MailCore2, and I am trying to figure out how to read the flags off of an individual email object that I am fetching.
Each MCOIMAPMessage *email that I fetch has a property on it called 'flags.' Flags is of type MCOMessageFlag. When I look up the definition of MCOMessageFlag, I find that it is a typedef enum:
typedef enum {
MCOMessageFlagNone = 0,
/** Seen/Read flag.*/
MCOMessageFlagSeen = 1 << 0,
/** Replied/Answered flag.*/
MCOMessageFlagAnswered = 1 << 1,
/** Flagged/Starred flag.*/
MCOMessageFlagFlagged = 1 << 2,
/** Deleted flag.*/
MCOMessageFlagDeleted = 1 << 3,
/** Draft flag.*/
MCOMessageFlagDraft = 1 << 4,
/** $MDNSent flag.*/
MCOMessageFlagMDNSent = 1 << 5,
/** $Forwarded flag.*/
MCOMessageFlagForwarded = 1 << 6,
/** $SubmitPending flag.*/
MCOMessageFlagSubmitPending = 1 << 7,
/** $Submitted flag.*/
MCOMessageFlagSubmitted = 1 << 8,
} MCOMessageFlag;
Since I do not know how typedef enums really work - particularly this one with the '= 1 << 8' type components, I am a little lost about how to read the emails' flags property.
For example, I have an email message that has both an MCOMessageFlagSeen and an MCOMessageFlagFlagged on the server. I'd like to find out from the email.flags property whether or not the fetched email has one, both or neither of these flags (if possible). However, in the debugger when I print 'email.flags' for an email that has both of the above flags, I get back just the number 5. I don't see how that relates to the typedef enum definitions above.
Ultimately, I want to set a BOOL value based on whether or not the flag is present. In other words, I'd like to do something like:
BOOL wasSeen = email.flags == MCOMessageFlagSeen;
BOOL isFlagged = email.flags == MCOMessageFlagFlagged;
Of course this doesn't work, but this is the idea. Can anyone suggest how I might accomplish this and/or how to understand the typedef enum?
These flags are used as in a bitmask.
This allows to store multiple on/off flags in a single numeric type (let it be an unsigned char or an unsigned int). Basically if a flag is set then its corresponding bit is set too.
For example:
MCOMessageFlagMDNSent = 1 << 5
1<<5 means 1 shifted to the left by 5 bits, so in binary:
00000001 << 5 = 00100000
This works only if no flag overlaps with other flags, which is typically achieved by starting with 1 and shifting it to the left by a different amount for every flag.
Then to check if a flag is set you check if the corresponding bit is set, eg:
if (flags & MCOMessageFlagMDNSent)
result will be true if the bitwise AND result is different from zero, this can happen only if the corresponding bit is set.
You can set a flag easily with OR:
flags |= MCOMessageFlagMDNSent;
or reset it with AND:
flags &= ~MCOMessageFlagMDNSent;
The values of the enum represent the individual bits, so you need bitwise operations to check for flags:
BOOL wasSeen = ( email.flags & MCOMessageFlagSeen ); // check if a bit was set
BTW: You code seems to suggest this is C, not C++. Tagging a question is both is almost always wrong, I suggest you pick the language you are using and remove the other tag.

Flags, enum (C)

I'm not very used to programming with flags, but I think I just found a situation where they'd be useful:
I've got a couple of objects that register themselves as listeners to certain events. What events they register for is dependent on a variable that is sent to them when they are constructed. I think a nice way to do this would be to send bitwise OR connected variables, like such: TAKES_DAMAGE | GRABBABLE | LIQUID, etc. Then, in the constructor, the object can check what flags are set and register it self as listener for the ones that are.
But this is where I get confused. Preferably, the flags would be in an enum. But that is also a problem. If we have got these flags:
enum
{
TAKES_DAMAGE,/* (0) */
GRABBABLE, /* (1) */
LIQUID, /* (2) */
SOME_OTHER /* (3) */
};
Then sending the flag SOME_OTHER (3) will be the same as sending GRABBABLE | LIQUID, will it not?
How exactly do you deal with this stuff?
Your enumeration needs to be powers of two :
enum
{
TAKES_DAMAGE = 1,
GRABBABLE = 2,
LIQUID = 4,
SOME_OTHER = 8
};
Or in a more readable fashion :
enum
{
TAKES_DAMAGE = 1 << 0,
GRABBABLE = 1 << 1,
LIQUID = 1 << 2,
SOME_OTHER = 1 << 3
};
Why ? Because you want to be able to combine flags with no overlapping, and also be able to do this:
if(myVar & GRABBABLE)
{
// grabbable code
}
... Which works if the enumeration values look like this :
TAKES_DAMAGE: 00000001
GRABBABLE: 00000010
LIQUID: 00000100
SOME_OTHER: 00001000
So, say you've set myVar to GRABBABLE | TAKES_DAMAGE, here's how it works when you need to check for the GRABBABLE flag:
myVar: 00000011
GRABBABLE: 00000010 [AND]
-------------------
00000010 // non-zero => converts to true
If you'd set myVar to LIQUID | SOME_OTHER, the operation would have resulted in :
myVar: 00001100
GRABBABLE: 00000010 [AND]
-------------------
00000000 // zero => converts to false
another way of storing flags is to not bother with the underlying type at all. when using an enum, the enum values are stored by default into an unsigned int, which is 32 bits on a common computer. this gives you with only 32 possible flags: while certainly much, there are some cases where it is not sufficient.
now you can define your flag set this way:
typedef struct
{
int takes_damage : 1;
int grabbable : 1;
int liquid : 1;
int some_other : 1;
} flags;
if you never encountered this, the ': 1' part tells the compiler to only use 1 bit to store this struct member.
now you can define a variable to hold the flags, and work with those flags:
flags myflags = {1,0,0,1}; // defines a variable holding a set of flags, with an initial value of takes_damage & some_other
myflags.liquid = 1; // change the flags to include the liquid
if ( myflags.takes_damage ) // test for one flag
apply_damage();
if ( myflags.liquid && myflags.some_other ) // test for multiple flags
show_strange_behavior();
this method allows you to define any number of flags, without limitation, and you can extend your flag set at any time without fearing an overflow. the drawback is that testing a subset of the flags is more cumbersome and necessitate more code.
Yes. Instead, make your enum members powers of 2:
enum
{
TAKES_DAMAGE = (1 << 0),
GRABBABLE = (1 << 1),
LIQUID = (1 << 2),
SOME_OTHER = (1 << 3)
};
You should make the flags only powers of two, i.e. each is a bit in whatever data type you're storing this in, and nothing overlaps when you bitwise OR.
Can't you just set the values in the enum?
enum {
TAKES_DAMAGE = 1,
GRABBABLE = 2,
LIQUID = 4
}
Afterwards, just perfom bit-wise OR on them.
you need
enum
{
TAKES_DAMAGE = 1,
GRABBABLE = 2,
LIQUID = 4,
SOME_OTHER = 8
};

Resources