# Article 127 - Programming - How to Use Bitmasks?

Bitmask is a concept often forgotten in common applications but are extremely effective when used properly.

The reader is encouraged to review Article 36 - Programming Bits for background understanding.

## Purpose of Using Bitmasking

The purpose of bitmask is reduce the memory consumption used by other primitive types such as a boolean. Bitmasking is often faster than the conventional primitive types as well.

For example, a boolean is often a redefined integer. An integer is normally 4 bytes in size, which is 32 bits. A boolean can be represented in 1 bit, as it is either true (non-zero) or false (zero). So, the other 31 bits are wasted.

To further explode this example, if we need multiple boolean variables such as 32 of them, then we would have essentially 32 integers but each only holding a single boolean value. That requires 32 * 4 bytes of space, which is 128 bytes, or 1024 bits in total.

Instead of having 32 boolean values, we can use a single integer (of equivalent size) with the bitmasking technique. Then only 32 bits are used instead of 1024 bits, saving 992 bits or almost 97%. On memory tight systems such as embedded systems, this is a must have requirement.

After fully understanding the reason to use bitmask, we need to explain how to use them.

## Set Operation

To set a bit, use the OR "|" operation, which effectively sets the bit at the particular location.

For example, if variable bitmask is 0x01, then "bitmask |= 0x10" becomes 0x11. You have set the 4th bit (from right to left) to 1.

## Check Operation

To check if a bit is set, use the AND "&" operation with an another bitmask that contains the bit(s) to be checked.

For example, if the variable bitmask is 0x01, then the expression "bitmask & 0x01" becomes true while "bitmask & 0x10" evaluates to false.

## Remove Operation

To remove a bit, a more complicated operation is required. Use the AND and NOT "~" operations. First apply the NOT operation to the bit location(s) you want to remove, and AND the operation with the variable, which effectively retains only the bits we did not want to remove.

For example, if the variable bitmask is 0x11 and we want to remove the first bit such that variable bitmask becomes 0x10, we apply the operations "bitmask &= ~0x01".

## Rules

Set Bit: OR operation.

Check Bit: AND operation.

Remove Bit: AND and NOT operation. 