代码之家  ›  专栏  ›  技术社区  ›  user195488

定义位0、位1、位2等,不带#Define

  •  2
  • user195488  · 技术社区  · 15 年前

    #define BIT0 0x00000001
    #define BIT1 0x00000002
    #define BIT2 0x00000004
    

    然后我拿同样的东西,用这些比特来做状态:

    #define MOTOR_UP   BIT0
    #define MOTOR_DOWN BIT1
    

    setBit(flagVariable, BIT) (因此a) clrBit

    if (flagVariable & MOTOR_UP) { 
       // do something
       clrBit(flagVariable, MOTOR_UP);
    }
    

    C++中有一个已经包含这些位掩码的类型吗?

    9 回复  |  直到 9 年前
        1
  •  6
  •   Loki Astari    15 年前

    怎么样:

    enum Bits
    {
        BIT0    = 0x00000001,
        BIT1    = 0x00000004,
        BIT2    = 0x00000008,
    
        MOTOR_UP    = BIT0,
        MOTOR_DOWN  = BIT1
    };
    
        2
  •  7
  •   Georg Fritzsche    15 年前

    enum {
      BIT1 = 1,
      BIT2 = 2,
      BIT3 = 4,
      ...
    };
    
        3
  •  6
  •   In silico    15 年前

    有一种方法:

    const int bit0 = (1<<0);
    const int bit1 = (1<<1);
    const int bit2 = (1<<2);
    //...
    
    const int motor_up = bit0;
    const int motor_down = bit1;
    
        4
  •  6
  •   Cogwheel    15 年前

    使用模板怎么样?

    template <int BitN>
    struct bit
    {
        static const int value = (1 << BitN);
    }
    

    你可以这样使用它:

    const int MOTOR_UP   = bit<0>::value;
    const int MOTOR_DOWN = bit<1>::value;
    

    或使用枚举:

    enum
    {
        MOTOR_UP   = bit<0>::value,
        MOTOR_DOWN = bit<1>::value
    }
    
        5
  •  5
  •   tzaman    15 年前

    可以改用函数:

    #define BIT(n) (1<<(n))
    

    为符合宏要求而编辑

        6
  •  2
  •   Community CDub    8 年前

    tzaman's Martin York's

    #define BIT(x) (1 << (x))
    
    enum {
        motor_up = BIT(0),
        motor_down = BIT(1)
    };
    

    没有什么特别的理由让一堆宏或枚举使用像这样愚蠢的名称 BIT0 , BIT1 , ..., BITn

    const int 类型)。

        7
  •  0
  •   Billy ONeal IS4    15 年前

    你可能想要像 STL's std::bitset .

        8
  •  0
  •   jyoung    15 年前

    union MotorControl
    {
        struct 
        {
            int motorUp :1;
            int motorDown :1;
        };
        struct 
        {
            int all;
        };
    };
    
    int main(array<System::String ^> ^args)
    {
        MotorControl mc;
        mc.all = 0;
        mc.motorDown = 1;
    }
    
        9
  •  -1
  •   Community CDub    8 年前

    我会修改马丁的 answer 就一点:

    enum Bits
    {
        BIT0    = 0x00000001,
        BIT1    = BIT0 << 1, 
        BIT2    = BIT1 << 1,
    
        MOTOR_UP    = BIT0,
        MOTOR_DOWN  = BIT1
    };
    

    使用shift操作符可以使事情更加一致,如果你跳过了一点,也会让事情变得更加明显。