Reputation: 183
I have the following enums:
Days:
Sunday 1
Monday 2
Tuesday 4
Wednesday 8
Thursday 16
Friday 32
Saturday 64
WeekOfMonth
First 256
Second 512
Third 1024
Fourth 2048
I have, for example, the number 514 which is a sum of 512(Second
) +2(Monday
).
How can I get Second & Monday if I only have the number 514?
Upvotes: 3
Views: 339
Reputation: 106916
Assuming the following definitions:
[Flags]
enum Days {
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
[Flags]
enum WeekOfMonth {
First = 256,
Second = 512,
Third = 1024,
Fourth = 2048
}
You can get the desired string using this code:
var value = (Int32) WeekOfMonth.Second + (Int32) Days.Monday; // 514
var days = (Days) (value & 0xFF);
var weekOfMonth = (WeekOfMonth) (value & 0xFF00);
var str = String.Format("{0} & {1}", weekOfMonth, days);
The variable str
will contain Second & Monday
as desired.
The [Flags]
attribute is important if you want to be able to combine several Days
values or WeekOfMonth
values. For instance ((Days) 3).ToString()
will return Sunday, Monday
. If you forget the [Flags]
attribute the string returned is 3
.
Upvotes: 6
Reputation: 1205
Untested but should work: Take the number and divide it by the int value of the first WeekOfMonth value. The result will be a double, ignore everthing behind the comma. Now you have the value for WeekOfMonth. Afterwards use mod (%) division to get the rest of the division to get the remaining value which represtns your Days value.
In code:
var intValue = (int)WeekOfMonth.Second + (int)Days.Monday; //514
var weekOfMonth = (WeekOfMonth)Convert.ToInt32(intValue / (int)WeekOfMonth.First);
var day = (Days)(intValue % (int)WeekOfMonth.First);
I'm not sure if all the casts are working but it should give you the idea ;)
Upvotes: 0
Reputation: 5916
You could do a logical AND against each possible value. All values that return non zero are the ones that you want.
var finalValue = ... // 512 -> 1000000010
var possibleValues = ... // array of flags [00000001, 000000010, 00000100, 00001000 ... ]
var appliedFlags = possibleValues.Where(x => x & finalValue == x).ToList();
Upvotes: 0
Reputation: 1692
well I have an idea as I can see it seems to be binary sequence , so you can subtract this number 514 to the nearest binary which will be 512 then do the same process to the remaining until you got 0.
Upvotes: 0