I’m consuming a web API and I need to pass in an int value that corresponds to a bit flag. How do I calculate the int values to pass in? For instance, if I want Option B, Option E, and Option F – what would the corresponding int value be?
Also please give a few more examples, like if I only want Option G. Or if I want D and E.
[Flags] public enum Includes
{
OptionA = 1 << 0,
OptionB = 1 << 1,
OptionC = 1 << 2,
OptionD = 1 << 3,
OptionE = 1 << 4,
OptionF = 1 << 5,
OptionG = 1 << 6,
OptionH = 1 << 7
}
int includes = ????
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
How do I calculate the int values to pass in?
By using bitwise OR, in that same way that this works:
int seven = 1|2|4;
Because in binary 1 is 0001, 2 is 0010 and 4 is 0100 when OR’d together they become 0111 (7)
Option B, Option E, and Option F
int bef = (int)(Includes.OptionB | Includes.OptionE | Includes.OptionF);
You can imagine the pattern you need to use for others. It doesn’t matter what order you OR them in
For decoding a number we use a similar trick with &:
if(bef & Includes.OptionB == Includes.OptionB)
There is a helper method Enum.HasFlag you can use too
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0