Bitflag to int C# - c#

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 = ????

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

Related

Enum Flags Negative Value

Got a negative number (-2147483392)
I don't understand why It (correctly) casts to a flags enum.
Given
[Flags]
public enum ReasonEnum
{
REASON1 = 1 << 0,
REASON2 = 1 << 1,
REASON3 = 1 << 2,
//etc more flags
//But the ones that matter for this are
REASON9 = 1 << 8,
REASON17 = 1 << 31
}
why does the following correctly report REASON9 and REASON17 based off a negative number?
var reason = -2147483392;
ReasonEnum strReason = (ReasonEnum)reason;
Console.WriteLine(strReason);
.NET Fiddle here
I say correctly, as this was an event reason property being fired from a COM component, and when cast as the enum value, it was correct in the values it casts to (as per that event). The flags enum was as per the SDK documentation for the COM object. The COM object is third party and I have no control over the number, based off the interface it will always be supplied as an INT
The topmost bit set (31-th in your case of Int32) means negative number (see two's complement for details):
int reason = -2147483392;
string bits = Convert.ToString(reason, 2).PadLeft(32, '0');
Console.Write(bits);
Outcome:
10000000000000000000000100000000
^ ^
| 8-th
31-th
And so you have
-2147483392 == (1 << 31) | (1 << 8) == REASON17 | REASON9

Mapping a bitfield to another bitfield in C#

I have two bitfields, one of 8 bits and one of 4 bits.
[Flags]
public enum Bits1 {
A = 1,
B = 2,
C = 4,
D = 8,
E = 16,
F = 32,
G = 64,
H = 128
}
[Flags]
public enum Bits2 {
I = 1,
J = 2,
K = 4,
L = 8
}
I need to map the bits in Bits1 to Bits2, like this:
Bits2 = Map(Bits1)
For example, supposing that A and C map to J, B maps to nothing, and D maps to I in the mapping, ABCD(value of 13), after going through the map function, returns IJ(value of 3).
The map should be able to be set and changed programmatically as needed. This sounds like something a Dictionary might be able to do, but I'm not sure how to set it up. What would be the best way to accomplish this in C#?
The best way is this. Use an array where the input is the index into the array and you output the value of the array:
public Bits2 Map(Bits1 input)
{
return _mapping[(int) input];
}
You have then to define the 16 mappings as follows (this is just an example):
private static Bits2[] _mapping = new Bits2[16]() {
Bits2.I | Bits2.J, // this is index 0, so all Bits1 are off
Bits2.K, // this is index 1, so all but A are off
Bits2.I | Bits2.L, // this is index 2, so all but B are off
Bits2.J | Bits2.K, // this is index 3, so all but A | B are off
// continue for all 16 combinations of Bits1...
};
The example shows how to encode the first 4 mappings:
none -> I | J
A -> K
B -> I | J
A | B -> J | K
What do you mean by
The map should be able to be set and changed programmatically as needed.
To me, it seems that the mapping is fixed by the definition of the enums. In your question, you don't specify how the code should behave if some flags are missing in the Bits2. In fact, Map function could be defined like this if you don't need to detect missing values:
public Bits2 Map(Bits1 input)
{
return (Bits2)(int)input;
}
Of course, if you need to detect missing value, then you can look at Enum class methods...

How to get list of string values from enum when all values are stored in on database field

Say I have the following enums which represents a combination of properties that can be assigned to an object.
public enum ObjectFlags
{
None = 0,
Red = 1 << 0, // 1
Square = 1 << 1, // 2
Small = 1 << 2, // 4
Fast = 1 << 3, // 8
}
I store any selected property in a SQL database field called ObjectFlag:
Say I passed in Red and Small enums to the SaveOjectFlags method and
storethe integer combination using bitwise in a field .
public ActionResult SaveOjectFlags(List<string> myflags)
{
ObjectFlags = myFlags;
foreach (var flag in ObjectFlags)
{
mydatabaseTable.ObjectFlag += (int) Enum.Parse(typeof (ObjectFlags), flag);
_dbRepo.Save();
}
}
Now I wish to get the values from my ObjectFlags field in my database and get the enums as a list of strings:
I have tried doing the following which didn’t quite work:
var test = (ObjectFlags)mydatabaseTable.ObjectFlag;
The values of the variable test above doesn't = a list of strings from the enum
What am I doing wrong here?
See here.
The solution is:
[Flags]
public enum ObjectFlags
{
None = 0,
Red = 1 << 0, // 1
Square = 1 << 1, // 2
Small = 1 << 2, // 4
Fast = 1 << 3, // 8
}
All I needed to do was add the [Flags] attribute as Jon Skeet suggested

Enum assignment looks different

How this enum is assigned? What are all the value for each?
public enum SiteRoles
{
User = 1 << 0,
Admin = 1 << 1,
Helpdesk = 1 << 2
}
What is the use of assigning like this?
Used in this post
They're making a bit flag. Instead of writing the values as 1, 2, 4, 8, 16, etc., they left shift the 1 value to multiply it by 2. One could argue that it's easier to read.
It allows bitwise operations on the enum value.
1 << 0 = 1 (binary 0001)
1 << 1 = 2 (binary 0010)
1 << 2 = 4 (binary 0100)

What is the tilde (~) in the enum definition?

I'm always surprised that even after using C# for all this time now, I still manage to find things I didn't know about...
I've tried searching the internet for this, but using the "~" in a search isn't working for me so well and I didn't find anything on MSDN either (not to say it isn't there)
I saw this snippet of code recently, what does the tilde(~) mean?
/// <summary>
/// Enumerates the ways a customer may purchase goods.
/// </summary>
[Flags]
public enum PurchaseMethod
{
All = ~0,
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4
}
I was a little surprised to see it so I tried to compile it, and it worked... but I still don't know what it means/does. Any help??
~ is the unary one's complement operator -- it flips the bits of its operand.
~0 = 0xFFFFFFFF = -1
in two's complement arithmetic, ~x == -x-1
the ~ operator can be found in pretty much any language that borrowed syntax from C, including Objective-C/C++/C#/Java/Javascript.
I'd think that:
[Flags]
public enum PurchaseMethod
{
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4,
All = Cash | Check | CreditCard
}
Would be a bit more clear.
public enum PurchaseMethod
{
All = ~0, // all bits of All are 1. the ~ operator just inverts bits
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4
}
Because of two complement in C#, ~0 == -1, the number where all bits are 1 in the binary representation.
Its better than the
All = Cash | Check | CreditCard
solution, because if you add another method later, say:
PayPal = 8 ,
you will be already done with the tilde-All, but have to change the all-line with the other. So its less error-prone later.
regards
Just a side note, when you use
All = Cash | Check | CreditCard
you have the added benefit that Cash | Check | CreditCard would evaluate to All and not to another value (-1) that is not equal to all while containing all values.
For example, if you use three check boxes in the UI
[] Cash
[] Check
[] CreditCard
and sum their values, and the user selects them all, you would see All in the resulting enum.
For others who found this question illuminating, I have a quick ~ example to share. The following snippet from the implementation of a paint method, as detailed in this Mono documentation, uses ~ to great effect:
PaintCells (clipBounds,
DataGridViewPaintParts.All & ~DataGridViewPaintParts.SelectionBackground);
Without the ~ operator, the code would probably look something like this:
PaintCells (clipBounds, DataGridViewPaintParts.Background
| DataGridViewPaintParts.Border
| DataGridViewPaintParts.ContentBackground
| DataGridViewPaintParts.ContentForeground
| DataGridViewPaintParts.ErrorIcon
| DataGridViewPaintParts.Focus);
... because the enumeration looks like this:
public enum DataGridViewPaintParts
{
None = 0,
Background = 1,
Border = 2,
ContentBackground = 4,
ContentForeground = 8,
ErrorIcon = 16,
Focus = 32,
SelectionBackground = 64,
All = 127 // which is equal to Background | Border | ... | Focus
}
Notice this enum's similarity to Sean Bright's answer?
I think the most important take away for me is that ~ is the same operator in an enum as it is in a normal line of code.
It's a complement operator,
Here is an article i often refer to for bitwise operators
http://www.blackwasp.co.uk/CSharpLogicalBitwiseOps.aspx
Also msdn uses it in their enums article which demonstrates it use better
http://msdn.microsoft.com/en-us/library/cc138362.aspx
The alternative I personally use, which does the same thing than #Sean Bright's answer but looks better to me, is this one:
[Flags]
public enum PurchaseMethod
{
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4,
PayPal = 8,
BitCoin = 16,
All = Cash + Check + CreditCard + PayPal + BitCoin
}
Notice how the binary nature of those numbers, which are all powers of two, makes the following assertion true: (a + b + c) == (a | b | c). And IMHO, + looks better.
I have done some experimenting with the ~ and find it that it could have pitfalls. Consider this snippet for LINQPad which shows that the All enum value does not behave as expected when all values are ored together.
void Main()
{
StatusFilterEnum x = StatusFilterEnum.Standard | StatusFilterEnum.Saved;
bool isAll = (x & StatusFilterEnum.All) == StatusFilterEnum.All;
//isAll is false but the naive user would expect true
isAll.Dump();
}
[Flags]
public enum StatusFilterEnum {
Standard =0,
Saved =1,
All = ~0
}
Each bit in [Flags] enum means something enabled (1) or disabled (0).
~ operator is used to invert all the bits of the number. Example: 00001001b turns into 11110110b.
So ~0 is used to create the value where all bits are enabled, like 11111111b for 8-bit enum.
Just want to add that for this type of enums it may be more convenient to use bitwise left shift operator, like this:
[Flags]
enum SampleEnum
{
None = 0, // 0000b
First = 1 << 0, // 0001b
Second = 1 << 1, // 0010b
Third = 1 << 2, // 0100b
Fourth = 1 << 3, // 1000b
All = ~0 // 1111b
}

Categories

Resources