Enum Flags Negative Value - c#

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

Related

Bitflag to int 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

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)

Determining which flags are missing from enum

Lets say i have the enum below:
[Flags]
public enum NotifyType
{
None = 0,
Window = 1 << 0,
Sound = 1 << 1,
Flash = 1 << 2,
MobileSound = 1 << 3,
MobilePush = 1 << 4
}
Considering two enums:
var myenums = Window | Sound | Flash;
//var possibleUpdate = Window | MobilePush;
void UpdateMyEnums(NotifyType possibleUpdate)
{
//Does myenums contain all the flags in 'possibleUpdate'? If not add
//the missing flags to myenums
}
How is it possible to determine that the myenums variable does not contain the NotifyType.MobilePush value in comparison to the possibleUpdate? Do i have to test each flag in possibleUpdate against myenums?
I am using C# on .NET 4.0
if (myenums & possibleUpdate != possibleUpdate)
//not a possible update
To get the flags needed not in myenums:
NotifyType missing = (~(myenums ^ wanted) ^ wanted) & (myenums | wanted);
There is no need to figure out which one is missing, you just need to do bit-wise OR between myenums and possibleUpdate and then assign the value back.
//Does myenums contain all the flags in 'possibleUpdate'?
if (myenums & possibleUpdate != possibleUpdate)
//If not add the missing flags to myenums
myenums = myenums | possibleUpdate;
In .NET 4+ you can use (and people will whinge about it being 10x slower than a manual operation, of course) you can use Enum.HasFlag, obviously negating the result.
The obvious answer is to simply bitwise-Or the needed flags. If you wanted a sequence of the missing flags, for say reporting:
var missing = Enum.GetValues(typeof(NotifyType)).Cast<NotifyType>()
.Where(nt => ((nt & possibleUpdate) == nt)
&& ((nt & myenums) == 0));
Console.WriteLine("Missing: {0}", String.Join(" | ", missing));
You can clean this up a bit with Enum.HasFlag:
var missing = Enum.GetValues(typeof(NotifyType)).Cast<NotifyType>()
.Where(nt => possibleUpdate.HasFlag(nt)
&& !myenums.HasFlag(nt));

How to parse byte using bits value

I have to get values from a byte saved in three parts of bit combination.
Bit Combination is following
| - - | - - - | - - - |
first portion contains two bits
Second portion contains 3 bits
Third portion contains 3 bits
sample value is
11010001 = 209 decimal
What I want is create Three different Properties which get me decimal value of three portion of given bit as defined above.
how can i get Bit values from this decimal number and then get decimal value from respective bits..
Just use shifting and masking. Assuming that the two-bit value is in the high bits of the byte:
int value1 = (value >> 6) & 3; // 3 = binary 11
int value2 = (value >> 3) & 7; // 7 = binary 111
int value3 = (value >> 0) & 7;
The final line doesn't have to use the shift operator of course - shifting by 0 bits does nothing. I think it adds to the consistency though.
For your sample value, that would give value1 = 3, value2 = 2, value3 = 1.
Reversing:
byte value = (byte) ((value1 << 6) | (value2 << 3) | (value3 << 0));
You can extract the different parts using bit-masks, like this:
int part1=b & 0x3;
int part2=(b>>2) & 0x7;
int part3=(b>>5) & 0x7;
This shifts each part into the least-significant-bits, and then uses binary and to mask all other bits away.
And I assume you don't want the decimal value of these bits, but an int containing their value. An integer is still represented as a binary number internally. Representing the int in base 10/decimal only happens once you convert to string.

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