Bitwise operators for options

There's a very useful technique that is available to developers that hardly anyone knows about these days.

Bitwise operators!

Basically what you are doing is manipulating the individual bits within a variable. Personally where I have found this extremely useful is for having a bunch of options and passing them around in a single integer variable.

For example, let's look at the orientation options of a mobile application:

Portrait for the first bit,
LandscapeRight for the second bit,
LandscapeLeft for the third bit,
PortraitUpsideDown for the fourth bit

We can represent an application that can only be in portrait mode, regardless if the device is upside down with the following:

1001 which equals an integer value of nine (9) or the sum of one (for the first bit) and eight (for the fourth bit)

To get this you could do the following:

int options;
options += 1 << 0;   //Portrait                      // 0001    // integer value of 1
options += 1 << 3;   //PortraitUpsideDown  // 1000    // integer value of 8

And then using bitwise operators ( | and & etc. note the single pipe and ampersand) you can then do logic based on certain option combinations or whatever.

This is an extremely useful technique to group relevant options of an object into a single variable, instead of multiple boolean property flags.

Some nice reading at learncpp

Comments