没有#define定义BIT0,BIT1,BIT2等

2 c++ bit-manipulation bitmap c-preprocessor

在C++中是否可以在不使用#define的情况下以C++的另一种方式定义BIT0,BIT1,BIT2?

#define BIT0 0x00000001
#define BIT1 0x00000002
#define BIT2 0x00000004
Run Code Online (Sandbox Code Playgroud)

然后,我采取同样的事情,并从这些位:

#define MOTOR_UP   BIT0
#define MOTOR_DOWN BIT1
Run Code Online (Sandbox Code Playgroud)

注意:我只使用32位,而不是64位.我也使用setBit(flagVariable, BIT)(因此clrBit宏做相反的)宏来设置位,然后比较是否使用按位运算符设置位,如

if (flagVariable & MOTOR_UP) { 
   // do something
   clrBit(flagVariable, MOTOR_UP);
}
Run Code Online (Sandbox Code Playgroud)

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

Sta*_*fan 7

您可以使用枚举:

enum {
  BIT1 = 1,
  BIT2 = 2,
  BIT3 = 4,
  ...
};
Run Code Online (Sandbox Code Playgroud)

  • *§7.2/ 4*表示:*"它是实现定义的,哪个整数类型用作枚举的基础类型,除了基础类型不应大于`int`,除非枚举器的值不能适合于`int`或`unsigned int`."* (9认同)

In *_*ico 6

这是一种方式:

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;
Run Code Online (Sandbox Code Playgroud)


Mar*_*ork 6

怎么样:

enum Bits
{
    BIT0    = 0x00000001,
    BIT1    = 0x00000004,
    BIT2    = 0x00000008,

    MOTOR_UP    = BIT0,
    MOTOR_DOWN  = BIT1
};
Run Code Online (Sandbox Code Playgroud)


Cog*_*eel 6

使用模板怎么样?

template <int BitN>
struct bit
{
    static const int value = (1 << BitN);
}
Run Code Online (Sandbox Code Playgroud)

你会这样使用它:

const int MOTOR_UP   = bit<0>::value;
const int MOTOR_DOWN = bit<1>::value;
Run Code Online (Sandbox Code Playgroud)

或者使用枚举:

enum
{
    MOTOR_UP   = bit<0>::value,
    MOTOR_DOWN = bit<1>::value
}
Run Code Online (Sandbox Code Playgroud)


tza*_*man 5

你可以改用一个函数:

#define BIT(n) (1<<(n))
Run Code Online (Sandbox Code Playgroud)

*编辑Macro Monster合规性

  • Macro Monster说,"我需要更多的parens!":`#define BIT(n)(1 <<(n))` (8认同)