1

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

Niels
  • 2,496
  • 5
  • 24
  • 38
  • 1
    What do you mean by 'remap'? Is it simply an issue of having lost the enum type, or is it an issue of getting a readable string description of the value? – Jean Hominal Dec 29 '13 at 17:45
  • here is a good solution: http://stackoverflow.com/questions/3261451/using-a-bitmask-in-c-sharp – Hegi Dec 29 '13 at 17:46

1 Answers1

7

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.

Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Could you include some sample code of how to use those Utility methods to produce the answer the OP is looking for? That'd be especially helpful. – George Stocker Dec 29 '13 at 17:48
  • @GeorgeStocker: It's not entirely clear exactly what the OP *does* want, to be honest - one variable? Three? – Jon Skeet Dec 29 '13 at 17:49
  • Also, `ToString()` on a `Flags` `enum` can produce "Wednesday, Thursday, Friday". – Cory Nelson Dec 29 '13 at 18:24
  • @CoryNelson: Yup - "Even just using `Console.WriteLine(days)` will give you a comma-separated representation." (Although I don't know what the ordering would be.) – Jon Skeet Dec 29 '13 at 18:26
  • Yes, I would like to get all variables :). Thanks! – Niels Dec 29 '13 at 18:56
  • 1
    @Niels: Well then see the loop that I've given near the end of the answer. – Jon Skeet Dec 29 '13 at 19:10
  • I really think hex (or bitshifting) is cleaner than decimal for representing flags ([like this](http://stackoverflow.com/a/13222740/18192)). – Brian Dec 30 '13 at 14:19
  • @Brian: I was just copying that aspect from the original question. They're semantically identical, of course. The important part of the answer is how to *use* those values. – Jon Skeet Dec 30 '13 at 15:22