[英]Enum Flags Negative Value
Got a negative number ( -2147483392
) 得到一个负数 (
-2147483392
)
I don't understand why It (correctly) casts to a flags enum
. 我不明白为什么它(正确)转换为标志
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 ? 为什么以下正确报告
REASON9
和REASON17
基于负数 ?
var reason = -2147483392;
ReasonEnum strReason = (ReasonEnum)reason;
Console.WriteLine(strReason);
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). 我说的正确 ,因为这是从一个COM组件被解雇事件的原因属性,当投为
enum
值,它是在它转换到(按该事件)的值是正确的 。 The flags enum was as per the SDK documentation for the COM object. 标志枚举是根据COM对象的SDK文档。 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
COM对象是第三方,我无法控制数字,基于接口,它将始终作为INT提供
The topmost bit set ( 31-th in your case of Int32
) means negative number (see two's complement for details): 最高位设置(在
Int32
的情况下为第31位)表示负数 (有关详细信息,请参见二进制补码 ):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.