Enum Flags Negative Value

2098 views c#
4

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

answered question

the topmost bit (31-th) set means negative number, see two's complement: en.wikipedia.org/wiki/Two%27s_complement

Why don't you specify the enum type rather than let the compiler do it for you and do it wrong.

@jdweng The compiler isn't doing anything wrong.

1 Answer

8

The topmost bit set (31-th in your case: 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) == REASON9 | REASON17

posted this

Have an answer?

JD

Please login first before posting an answer.