Why do enum permissions often have 0, 1, 2, 4 values?

前端 未结 7 949
你的背包
你的背包 2020-12-04 05:53

Why are people always using enum values like 0, 1, 2, 4, 8 and not 0, 1, 2, 3, 4?

Has this something to do with bit operations, etc.?

7条回答
  •  难免孤独
    2020-12-04 06:09

    Lot's of good answers to this one… I'll just say.. if you do not like, or cannot easily grasp what the << syntax is trying to express.. I personally prefer an alternative (and dare I say, straightforward enum declaration style)…

    typedef NS_OPTIONS(NSUInteger, Align) {
        AlignLeft         = 00000001,
        AlignRight        = 00000010,
        AlignTop          = 00000100,
        AlignBottom       = 00001000,
        AlignTopLeft      = 00000101,
        AlignTopRight     = 00000110,
        AlignBottomLeft   = 00001001,
        AlignBottomRight  = 00001010
    };
    
    NSLog(@"%ld == %ld", AlignLeft | AlignBottom, AlignBottomLeft);
    

    LOG 513 == 513

    So much easier (for myself, at least) to comprehend. Line up the ones… describe the result you desire, get the result you WANT.. No "calculations" necessary.

提交回复
热议问题