defining flags

Posted By: MPQ

defining flags - 04/21/13 16:20

Hi,

I want to use a variable which functions as a bit field. I read that I cannot use enum for that, but how do I define these in lite-c?

eg

enum status = { STAT_1 = 0x01, STAT_" = 0x04 , ...}

Thanks!
Posted By: Uhrwerk

Re: defining flags - 04/21/13 17:18

Code:
define CONST_1 1
define CONST_2 2
// etc.


Then you can combine the flags with the binary operators.
Posted By: Superku

Re: defining flags - 04/21/13 18:31

For those who are not aware the 3rd flag would have to be 4, not 3. The 4th flag would be 8 and so on, i.e. 2^n.

Alternatively you can use the bit shift operator the same way as it is used in atypes.h:

Code:
#define FLAG1			(1<<0)	// flag1..flag8 for C-Script use
#define FLAG2			(1<<1)
#define FLAG3			(1<<2)
#define FLAG4			(1<<3)
#define FLAG5			(1<<4)
#define FLAG6			(1<<5)
#define FLAG7			(1<<6)
#define FLAG8			(1<<7)

#define INVISIBLE		(1<<8)
#define PASSABLE		(1<<9)
#define TRANSLUCENT	(1<<10)	// transparent
#define OVERLAY		(1<<12)
...

Posted By: HeelX

Re: defining flags - 04/22/13 19:23

Originally Posted By: MPQ
I want to use a variable which functions as a bit field
Make sure that the variable type holds all flags. An int holds 4 bytes (32bit) and a long holds 8 bytes (64bit). If you just have 8 flags, use a char, because that is stored as 1 byte. Especially in network scenarios such consideration are interesting.

Originally Posted By: MPQ
I read that I cannot use enum for that, but how do I define these in lite-c?

Enums are not supported in Lite-C and they aren't flags. They are just constant names assigned to a numeric integer value. So if you have in C/C++ e.g.
Code:
enum { Apple, Orange, Banana, Melon } Fruit;


you could do something like that:
Code:
Fruit fruit = Apple;



Internally, they translate to constants like 0, 1 and 2. So, to emulate enums in Lite-C, you could do this, although it involves more writing:
Code:
#define Apple 1
#define Orange 3
#define Banana 5
#define Melon 7

typedef int Fruit;

Fruit fruit = Apple;

if (fruit == Melon)
   error("Shh you got to, shake it, shh shake it, shake it, got to shake it");
else
   if (fruit == Banana)
      error("(Shake it sugar) shake it like a Polaroid Picture");

© 2024 lite-C Forums