Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

You could use a function instead:

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

*edited for Macro Monster compliance

like image 106
tzaman Avatar answered Mar 24 '26 07:03

tzaman


You could use an enum instead:

enum {
  BIT1 = 1,
  BIT2 = 2,
  BIT3 = 4,
  ...
};
like image 40
Staffan Avatar answered Mar 24 '26 08:03

Staffan