gpt4 book ai didi

c# - 枚举标志负值

转载 作者:行者123 更新时间:2023-11-30 14:21:58 26 4
gpt4 key购买 nike

得到一个负数 (-2147483392)

我不明白为什么它(正确地)转换为标志 enum

给定

[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
}

为什么以下内容根据 负数 正确报告 REASON9REASON17

var reason = -2147483392;
ReasonEnum strReason = (ReasonEnum)reason;
Console.WriteLine(strReason);

.NET fiddle here

我说正确,因为这是从 COM 组件触发的事件原因属性,当转换为 enum 值时,它是正确 在它转换到的值中(根据该事件)。标志枚举是根据 COM 对象的 SDK 文档。 COM 对象是第三方的,我无法控制数字,基于接口(interface)它将始终作为 INT 提供

最佳答案

最高位集(第 31 位,在您的 Int32 情况下)表示负数(有关详细信息,请参阅 two's complement):

  int reason = -2147483392;

string bits = Convert.ToString(reason, 2).PadLeft(32, '0');

Console.Write(bits);

结果:

  10000000000000000000000100000000
^ ^
| 8-th
31-th

所以你有

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

关于c# - 枚举标志负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com