Bit-masking Cheatsheet from Evan Prodromou

Use a bit-mask Mask (computing) when you want to store a lot of boolean flags in a single integer.

Examples below are C-ish; convert to your preferred language.

Define constants

Life is a lot easier when you define constants for each bit in your flags variable.

 #define FOO_FLAG 1
 #define BAR_FLAG 2
 #define BAZ_FLAG 4
 #define QUUX_FLAG 8

Remember to go up by powers of two. Easiest to start from bit zero.

Use logical AND to check a flag's value

To check if a flag is set, use bitwise logical AND.

 if (my_flags & FOO_FLAG) {
    /* do something */
 }

Use logical OR to set a flag to TRUE

To set a flag value to true, use bitwise logical OR.

 my_flags = my_flags | QUUX_FLAG;

or

 
 my_flags |= QUUX_FLAG;

Use logical AND and NOT to set a flag to FALSE

To set a flag value to false, use bitwise logical AND on the bitwise inverse of the flag constant.

 my_flags = my_flags & ~BAR_FLAG;

or

 my_flags &= ~BAR_FLAG;