Best way to 'remap' a simple binary mask?
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.
链接地址: http://www.djcxy.com/p/54890.html上一篇: 按时间分组消息的算法