简体   繁体   中英

C# Operators Bitwise

I've been looking over some game programming code and have seen enums as in:

[Flags]
public enum CollisionCategories
{
    Cat1 = (1 << 0),
    Cat2 = (1 << 1),
    Cat3 = (1 << 2),
    Cat4 = (1 << 3),
    ...
}

Now, would this not be the same as just setting each item like 1, 2, 4, 8, ... ? I've seen the later as well. I know doing something like string s = string.Empty is better than string s = "" as far as performance goes but not sure about the enum.

Any thoughts?

Thanks much,

David

You are correct about the values that are stored. It would not make a difference in performance, so it is a readability issue that may make more sense in the context of the code.

It's just easier when you get to the larger numbers.

I'm sure that (1<< 24) is simpler than going to your calculator, calculating it, and pasting.

For some people, setting them this way is just cleaner than the typical C raw hex/decimal number initialization. (0x1,0x4000,etc) Since the compiler recognizes a literal and turns them into plain numbers, there's no performance drawback, it's just a style matter.

Yes it is the same.

I personally would use 1,2,4,8... because I think these numbers are so much well known that no one can misunderstand what's going on.

Performance is the same. Code size is the same.

Yes, it is the same. It's just so the code is more readable.

I think String.Empty is equivalent to "" the compiler will recognise the literal and convert it..... Anyway, it's the same for you enum, it's just a question of style and in the case of the enum it makes it 100% explicit that these are bit flags I suppose.

Or maybe the coder wasn't confident with his powers of 2, and couldn't be bothered to work them out.

Performance is not an issue here. Enum is compiled as a constant so it is the compiler that is doing the job hence no difference in runtime performance.

Alternative could have been using the power but since that involves code, it would not work:

enum MyEnum{
  Val1 = Math.Pow(1,2) // throws compile error
}

Error 1 The expression being assigned to 'ConsoleApplication1.Program.MyEnum.Val1' must be constant C:\\Users\\Aliostad\\Documents\\Visual Studio 2010\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs 130 11 ConsoleApplication1

Enum values must be constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM