枚举转换为错误的枚举

时间:2013-06-20 12:43:04

标签: c# enums binary

我使用枚举作为标志:

[Flags]
public enum Partition_Status_ConditionEnum : long
{
    Bypass_code_required = 1 << 0,
    Fire_trouble = 1 << 1,
    Fire = 1 << 2,
    Pulsing_Buzzer = 1 << 3,
    TLM_fault_memory = 1 << 4,
    Reserved = 1 << 5,
    Armed = 1 << 6,
    Instant = 1 << 7,

    Previous_Alarm = 1 << 8,
    Siren_on = 1 << 9,
    Steady_siren_on = 1 << 10,
    Alarm_memory = 1 << 11,
    Tamper = 1 << 12,
    Cancel_command_entered = 1 << 13,
    Code_entered = 1 << 14,
    Cancel_pending = 1 << 15,

    Silent_exit_enabled = 1 << 17,
    Entryguard = 1 << 18,
    Chime_mode_on = 1 << 19,
    Entry = 1 << 20,
    Delay_expiration_warning = 1 << 21,
    Exit1 = 1 << 22,
    Exit2 = 1 << 23,

    LED_extinguish = 1 << 24,
    Cross_timing = 1 << 25,
    Recent_closing_being_timed = 1 << 26,
    Exit_error_triggered = 1 << 28,
    Auto_home_inhibited = 1 << 29,
    Night_mode = 1 << 31,

    Re_exit_active = 1 << 32,
    Force_arm_triggered_by_auto_arm = 1 << 33,
    Ready_to_arm = 1 << 34,
    Ready_to_force_arm = 1 << 35,
    Valid_PIN_accepted = 1 << 36,
    Chime_on = 1 << 37,
    Error_beep = 1 << 38,
    Tone_on = 1 << 39,

    Entry_1 = 1 << 40,
    Open_period = 1 << 41,
    Alarm_sent_using_phone_number_1 = 1 << 42,
    Alarm_sent_using_phone_number_2 = 1 << 43,
    Alarm_sent_using_phone_number_3 = 1 << 44,
    Zone_bypassed = 1 << 45,
    Keyswitch_armed = 1 << 46,
    Delay_Trip_in_progress = 1 << 47,
}

但是当我将它们添加到列表中时

   List<Partition_Status_ConditionEnum> PartitionConditionList = new List<Partition_Status_ConditionEnum>();
   PartitionConditionList.Add(Partition_Status_ConditionEnum.Valid_PIN_accepted);
   PartitionConditionList.Add(Partition_Status_ConditionEnum.Cancel_pending);
   PartitionConditionList.Add(Partition_Status_ConditionEnum.Exit2);
   PartitionConditionList.Add(Partition_Status_ConditionEnum.Auto_home_inhibited);
   PartitionConditionList.Add(Partition_Status_ConditionEnum.Error_beep);

   Byte[] Message = Msg.BuildMessage(true, PartitionNumber, LastUserNumber, PartitionConditionList);

Valid_Pin_Accepted被视为TLM_Fault_Memory,Error_Beep被视为Armed。 我错过了什么?

enter image description here

3 个答案:

答案 0 :(得分:5)

使用long常量:1L << 36

http://ideone.com/3Bwbky

答案 1 :(得分:4)

你的文字是32位,所以1&lt;&lt;例如,42是32位数,并且与1&lt; 1&lt; 1&lt; (42 - 32)。因此,您的一些枚举值具有重复值。

为避免此行为,将其中一个文字提升为long类型:1L&lt;&lt; 42会这样做。

答案 2 :(得分:0)

如果您尝试进行逐位表示,则不需要使用列表。您需要使用二进制OR运算。你应该改为:

PartitionCondition = Partition_Status_ConditionEnum.Valid_PIN_accepted | 
   Partition_Status_ConditionEnum.Cancel_pending |
   Partition_Status_ConditionEnum.Exit2 | 
   Partition_Status_ConditionEnum.Auto_home_inhibited |
   Partition_Status_ConditionEnum.Error_beep;