Why use the Bitwise-Shift operator for values in a C enum definition?

前端 未结 8 1227
眼角桃花
眼角桃花 2020-12-02 10:42

Apple sometimes uses the Bitwise-Shift operator in their enum definitions. For example, in the CGDirectDisplay.h file which is part of Core

相关标签:
8条回答
  • 2020-12-02 11:18

    New in C# 7 is finally adding binary literals, so you can just write it as this:

    enum MyEnum
    {
        kCGDisplayBeginConfigurationFlag  = 0b0000000000000001;
        kCGDisplayMovedFlag               = 0b0000000000000010;
        kCGDisplaySetMainFlag             = 0b0000000000000100;
        kCGDisplaySetModeFlag             = 0b0000000000001000;
        kCGDisplayAddFlag                 = 0b0000000000010000;
        kCGDisplayRemoveFlag              = 0b0000000000100000;
        kCGDisplayEnabledFlag             = 0b0000000001000000;
        kCGDisplayDisabledFlag            = 0b0000000010000000;
        kCGDisplayMirrorFlag              = 0b0000000100000000;
        kCGDisplayUnMirrorFlag            = 0b0000001000000000;
        kCGDisplayDesktopShapeChangedFlag = 0b0000010000000000;
    };
    

    And if you want to make things even neater, you use this: _ which is also new to C# 7, which allows you to put spaces in numbers to make things more readable, like so:

    enum MyEnum
    {
        kCGDisplayBeginConfigurationFlag  = 0b_0000_0000_0000_0001;
        kCGDisplayMovedFlag               = 0b_0000_0000_0000_0010;
        kCGDisplaySetMainFlag             = 0b_0000_0000_0000_0100;
        kCGDisplaySetModeFlag             = 0b_0000_0000_0000_1000;
        kCGDisplayAddFlag                 = 0b_0000_0000_0001_0000;
        kCGDisplayRemoveFlag              = 0b_0000_0000_0010_0000;
        kCGDisplayEnabledFlag             = 0b_0000_0000_0100_0000;
        kCGDisplayDisabledFlag            = 0b_0000_0000_1000_0000;
        kCGDisplayMirrorFlag              = 0b_0000_0001_0000_0000;
        kCGDisplayUnMirrorFlag            = 0b_0000_0010_0000_0000;
        kCGDisplayDesktopShapeChangedFlag = 0b_0000_0100_0000_0000;
    };
    

    Makes it so much easier to keep track of the numbers.

    0 讨论(0)
  • 2020-12-02 11:21

    using #define is more understandable. but enum could group these value togater.

    0 讨论(0)
提交回复
热议问题