Bit Masks

Bit Masks

Bit masks are a computer science concept; in a nutshell, they represent options which can be combined in a variety of ways.

A very basic example colors. Blue and Green combined create yellow. This can be represented in bit masks.

The following example is sourced from the Bit field article on Wikipedia; it illustrates the concept well for those new to it.

Consider the following[1] and take note of the binary version which is in the comment.

// primary colors
#define BLUE  4  /* 100 */
#define GREEN 2  /* 010 */
#define RED   1  /* 001 */

This creates the base options. The next example uses the above to further define more colors without assigning them specific numbers, although they would output as numbers.

// mixed colors
#define BLACK   0                    /* 000 */
#define YELLOW  (RED | GREEN)        /* 011 */
#define MAGENTA (RED | BLUE)         /* 101 */
#define CYAN    (GREEN | BLUE)       /* 110 */
#define WHITE   (RED | GREEN | BLUE) /* 111 */

Notice that WHITE is all the colors -- all the bits are "on" and black is no color -- all the bits are off.

I've seen this used quite a bit although, I must admit, I don't come across it quite as often as I used to. Rest assured, it is still in use and is quite useful.


  1. The code presented is Pseudocode. It is not intended to be complete. ↩︎