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++中是否有一个已包含这些位掩码的类型?
您可以使用枚举:
enum {
BIT1 = 1,
BIT2 = 2,
BIT3 = 4,
...
};
Run Code Online (Sandbox Code Playgroud)
这是一种方式:
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)
怎么样:
enum Bits
{
BIT0 = 0x00000001,
BIT1 = 0x00000004,
BIT2 = 0x00000008,
MOTOR_UP = BIT0,
MOTOR_DOWN = BIT1
};
Run Code Online (Sandbox Code Playgroud)
使用模板怎么样?
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)
你可以改用一个函数:
#define BIT(n) (1<<(n))
Run Code Online (Sandbox Code Playgroud)
*编辑Macro Monster合规性