Reputation: 4921
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
Upvotes: 3
Views: 646
Reputation: 186748
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
Upvotes: 6