0

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.

Jamie
  • 674
  • 1
  • 10
  • 30

2 Answers2

2

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;
justin.lovell
  • 675
  • 3
  • 11
1

In C# use Enum.HasFlag(v). It will return if a enum has the value v set.

See documentation on MSDN

DrKoch
  • 9,556
  • 2
  • 34
  • 43
  • 2
    Don't use `Enum.HasFlag` if you care about performance as it uses reflection (e.g. [this](http://stackoverflow.com/q/7368652/1364007) SO question). Use a bitwise operator instead. – Wai Ha Lee Mar 08 '15 at 10:51