문제

I got a very simple binary mask.

1 = Sunday

2 = Saturday

4 = Friday

8 = Thursday

16 = Wednesday

32 = Tuesday

64 = Monday

So if you want a combination of Wednesday, Thursday and Friday you get 16 + 8 + 4 = 28

Now further along my code I only have the mapped binary value. What would be the best way to 'remap' this value (28) to Wed, Thu and Fri?

Hope to get some input on how to do this :).

Kind regards, Niels

도움이 되었습니까?

해결책

You should use an enum:

[Flags]
public enum WeekDays
{
    Sunday = 1,
    Saturday = 2,
    Friday = 4,
    Thursday = 8,
    Wednesday = 16,
    Tuesday = 32,
    Monday = 64
}

A simple explicit conversion will do the "remapping" you're interested in:

WeekDays days = (WeekDays) 28;

You can easily use normal bitwise operations:

if ((days & WeekDays.Friday) != 0)
{
    // Yes, the mask included Friday
}

And you could do that in a loop:

foreach (WeekDays day in Enum.GetValues(typeof(WeekDays))
{
    if ((days & day) != 0)
    {
        Console.WriteLine("Got {0}", day);
    }
}

Even just using Console.WriteLine(days) will give you a comma-separated representation.

You may also find the utility methods in my Unconstrained Melody library useful (in particular the Flags code).

If you're looking for something else, please be more specific.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top