1

I have an enum type with some discontinued values for each enum. When I try to cast an int value to the enum type it returns with multiple enum values seperated with the | operator. Can anyone explain this logic of how it is cast?

enum EnumTest
{
    Test1 = 0,
    Test2 = 1,
    Test3 = 1 << 1,
    Test4 = 1 << 2,
    Test5 = 1 << 12,
    Test6 = 1 << 13,
    Test7 = 1 << 20,
    Test8 = 1 << 22,
    Test9 = 1 << 23,
    Test10 = 1 << 24,
    Test11 = 1 << 25,
    Test12 = 1 << 14,
    Test13 = 1 << 15,
    Test14 = 1 << 16,
    Test15 = 1 << 25,
    Test16 = 1 << 17,
    Test17 = 1 << 18,
    Test18 = 1 << 19,
    Test19 = 1 << 21,
    Test20 = 1 << 26
}

public void method1()
{
    int number=67239937;
    EnumTest e = (EnumTest)number; //output: Test2|Test16|Test20
}
3
  • 1
    The question isn't a direct dupe but the current accepted answer covers your question. Commented May 10, 2017 at 9:54
  • 1
    Also related: stackoverflow.com/questions/29482/… Commented May 10, 2017 at 9:55
  • The "logic" involved in the cast, incidentally, is really simple -- there is no logic. e has the value 67239937 under the covers. The actual mapping to the enum tags is of no concern to the compiler -- enums are really just dolled up integers. It's when the value is interpreted by other pieces of code that the tags come into play. Commented May 10, 2017 at 9:57

1 Answer 1

3

Let's say your enum is this:

enum E {
    A = 1
    B = 2
    C = 4
    D = 8
}

If you translate each value to it's binary value, you get:

A = 0001
B = 0010
C = 0100
D = 1000

Now let's say you try to convert 12, 1100 in binary, to this enum:

E enumTest = (E)12;

It will output C|D

| being the OR operator, C|D would mean 0100 OR 1000, which gives us 1100, or 12 in decimal.

In your case, it's just trying to find which enum combination is equal to 67239937. This is converted to binary as 100000000100000000000000001. This then converts to Test2|Test16|Test20 or 1|(1 << 17)|(1 << 26).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.