Enum Flags Negative Value

2098 views c#

Got a negative number (-2147483392)

I don't understand why It (correctly) casts to a flags enum.


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;

.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


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');



  ^                      ^
  |                      8-th

And so you have

  2147483392 == (1 << 31) | (1 << 8) == REASON9 | REASON17

posted this

Have an answer?


Please login first before posting an answer.