开发者

Define BIT0, BIT1, BIT2, etc Without #define

Is it possible in 开发者_运维知识库C++ to define BIT0, BIT1, BIT2 in another way in C++ without using #define?

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

I then take the same thing and make states out of those bits:

#define MOTOR_UP   BIT0
#define MOTOR_DOWN BIT1

Note: I am using 32 bits only, not 64 bits. I am also using a setBit(flagVariable, BIT) (consequently a clrBit macro to do the opposite) macro to set the bits then compare whether the bit is set using the bitwise operator such as

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

Is there a type in C++ that already contains these bit masks?


You could use an enum instead:

enum {
  BIT1 = 1,
  BIT2 = 2,
  BIT3 = 4,
  ...
};


How about:

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

    MOTOR_UP    = BIT0,
    MOTOR_DOWN  = BIT1
};


Here's one way:

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;


You could use a function instead:

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

*edited for Macro Monster compliance


How about using a template?

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

You would use it thus:

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

Or with an enum:

enum
{
    MOTOR_UP   = bit<0>::value,
    MOTOR_DOWN = bit<1>::value
}


I say combine tzaman's and Martin York's answers:

#define BIT(x) (1 << (x))

enum {
    motor_up = BIT(0),
    motor_down = BIT(1)
};

There's no particular reason for a bunch of macros or enums with silly-names like BIT0, BIT1, ..., BITn.

And enums work great as integral constants - they don't have macro global-namespace-stomping powers and they work equally well in C and C++ (which isn't true for const int types).


You probably want something like the STL's std::bitset.


Use bitfield union and structs. (For Billy: The solution to the problem is C++ code. The sample was using C++/CLI.)

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;
}


I'd modify Martin's answer just a bit:

enum Bits
{
    BIT0    = 0x00000001,
    BIT1    = BIT0 << 1, 
    BIT2    = BIT1 << 1,

    MOTOR_UP    = BIT0,
    MOTOR_DOWN  = BIT1
};

Using the shift operators makes things a little more consistent, and makes it obvious if you are skip a bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜