Skip to content

Instantly share code, notes, and snippets.

@ctkjose
Last active January 6, 2019 20:20
Show Gist options
  • Save ctkjose/fb9b1250ef154c9799d31c8f28f50b3a to your computer and use it in GitHub Desktop.
Save ctkjose/fb9b1250ef154c9799d31c8f28f50b3a to your computer and use it in GitHub Desktop.
Bitwise Masks

Using an Integer to store various indicators

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment