We use an integer variable to store options using its bits.
A mask is an integer with one or more bits set to 1. Each bit represents a particular option or state.
An integer in C holds at least 16 bits (4 bytes);
int maskOptionIsReadable = 0x80; //1000 0000
int maskOptionIsWritable = 0x40; //0100 0000
int maskOptionIsPrivate = 0x20; //0010 0000
//or using define
#define maskOptionIsReadable 0x80
#define maskOptionIsWritable 0x40
#define maskOptionIsPrivate 0x20
We set our options using a bitwise OR operation:
int flag = 0;
flag = flag | maskOptionIsReadable;
Use Multiple OR in one statement to set various options:
int flag = 0;
flag = flag | maskOptionIsReadable | maskOptionIsWritable;
Test if a variable has an option using a bitwise AND operation:
if( (flag & maskOptionIsReadable) == maskOptionIsReadable ){
printf("flag has the OptionIsReadable\n");
}else{
printf("flag does not have the OptionIsReadable\n");
}
Unset an option using a bitwise XOR operation:
flag = flag ^ maskOptionIsReadable;
When using bitwise masks to store data you have to take into account the endianness of the architecture. If the data is written and read by systems of different endianness you have to ensure that you operate using the same endianness to read and write bitwise masks.