Reputation: 724
I've got some code in another language which uses an enum and a list of values from the enum and then uses bitwise to get an integer for the list of values from the enum.
HELLO = 1
WORLD = 2
AND = 4
SO = 8
ON = 16
So if I had HELLO and SO in my list I'd get a value back of
1 | 1000 = 1001
1001bin to dec = 9
I'm trying to work out what the most efficient way of taking this integer and giving back a list of the enums which were included.
Upvotes: 0
Views: 66
Reputation: 675
Assuming that you want to work with the enums directly, the base types of all enums are integers. With this knowledge, you can take the "unbounded" nature of integers and bring the goodness of enums.
enum Greetings {
HELLO = 1,
WORLD = 2,
AND = 4,
SO = 8,
ON = 16
}
So if you get an integer back from the callee (doing interop?), you can then do this:
Greetings greet = (Greetings)theIntegerResult;
From there on, you can do your bitwise operations to see which fields are set.
bool isHelloSet = (greet & Greetings.HELLO) == Greetings.HELLO;
bool isWorldSet = (greet & Greetings.WORLD) == Greetings.WORLD;
bool isAndSet = (greet & Greetings.AND) == Greetings.AND;
bool isSoSet = (greet & Greetings.SO) == Greetings.SO;
bool isOnSet = (greet & Greetings.ON) == Greetings.ON;
Upvotes: 2
Reputation: 9772
In C# use Enum.HasFlag(v)
. It will return if a enum has the value v
set.
Upvotes: 1