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

前端 未结 8 1314
眼角桃花
眼角桃花 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:14

    Let's me give you a more practice example. In c++ when you want to open a file (Open for output, and in binary mode opposed to text mode), you can do it by:

    const char *filename = "/home/xy/test.bin";
    fstream output(filename, ios::out | ios::binary);
    

    You can see, ios::out | ios::binary can set two mode(Open for output, and in binary mode).

    How does this work ? It's by enum(bitwise-shift values):

    enum _Ios_Openmode 
    { 
      _S_app        = 1L << 0,
      _S_ate        = 1L << 1,
      _S_bin        = 1L << 2,  /* 0b0000000000000100 */
      _S_in         = 1L << 3,
      _S_out        = 1L << 4,  /* 0b0000000000010000 */
      _S_trunc      = 1L << 5
      //.....
    };
    
    /// Perform input and output in binary mode (as opposed to text mode).
    static const openmode binary =  _S_bin;
    
    /// Open for input.  Default for @c ifstream and fstream.
    static const openmode in =      _S_in;
    
    /// Open for output.  Default for @c ofstream and fstream.
    static const openmode out =     _S_out;
    

    If you use value increment by 1 in enum _Ios_Openmode, you have to set(ios::out) and set(ios::binary) do two times. It may not so convenient to check and set value by one time.

提交回复
热议问题