如何将这几天转换为位掩码?

时间:2012-08-05 13:05:14

标签: c# .net c#-4.0 bit-manipulation bitmask

我有一个使用枚举将位掩码转换为天数列表的方法。我正在尝试反过来,但我遇到了麻烦。我DaysOfWeekToEnum正在工作,但不是DaysOfWeekFromEnum。以下是我想要做的事情。有人可以帮忙吗?

public static short DaysOfWeekFromEnum(IEnumerable<DaysInWeekIds> daysOfWeek)
{
    short mask;

    foreach (var item in daysOfWeek)
    {
        mask &= item; // ????
    }

    return mask
}

public static IEnumerable<DaysInWeekIds> DaysOfWeekToEnum(short mask)
{
    var values = new List<DaysInWeekIds>();

    foreach (short enumValue in Enum.GetValues(typeof(DaysInWeekIds)))
    {
        if (mask & enumValue == enumValue)
        {
            values.Add((DaysInWeekIds) Enum.ToObject(typeof(DaysInWeekIds),
                enumValue));
        }
    }

    return values;
}

/// <summary> The days in week ids. </summary>
public enum DaysInWeekIds : short
{
    M = 1,
    Tu = 2,
    W = 4,
    Th = 8,
    F = 16,
    Sa = 32,
    Su = 64
}

1 个答案:

答案 0 :(得分:2)

设置附加位应为|=,而不是&=

您还可以将字符串表示连接在一起,并将结果传递给Enum.Parse方法。这不是那么有效,但代码看起来会更短。

var res = (DaysInWeekIds)Enum.Parse(
    typeof(DaysInWeekIds)
,   string.Join(",", daysOfWeek.Select(d => d.ToString()).ToArray())
);

这会为25link to ideone)返回{M, Th, F}