Bit masking is a binary operation that modifies some bits of a register without changing the others. This type of operation is found in microcontroller programming and in many libraries. There are 3 types of masking:

Example

Let's assume an 8-bit register named PORTA that drives leds.

• The least significant bit drives the led 0
• The second least significant bit drives the led 1
• ...
• The most significant bit drives the led 7

Nous supposerons que ce registre est accessible en lecture et en écriture.

• En lecture, il est possible de connaître l'état des leds.
• En écriture, il est possible de piloter les leds.

Voici quelques exemples d'écritures dans le registre :

• PORTA = 0x00; turns off all leds
• PORTA = 0x01; turns on the led 0
• PORTA = 0x08; turns on the led 1
• PORTA = 0x0F; turns on the 4 leds on the right
• PORTA = 0xFF; turns on all leds

Assume that we want to turn off the led n 2, without modifying the others. We understand quickly that if we write PORTA = 0x00;, we turn off led n°2, but also all the the others!

This is where masking comes in. The solution consists in performing a bitwise AND between the PORTA and a binary word (called mask). Here is a representation of the masking operation:

The binary operation is detailed below. We see that the result of the logical AND between PORTA and the mask turns off led n°2 without modification of the other bits :

$$\begin{array}[t]{r} 0101\:0101 \\ \& \; 1111\:1011 \\ \hline 0101\: 0001 \end{array}$$

In C, we write :

PORTA = PORTA & 0xFB;

Exercise

Modify the program in the example above to set bit 6 to 0 instead of the bit 2.

Quiz

What is the primary interest of bit masking?

What are the basic types of bit masking?

In the following masking, what is the operand 0xFE called?

reg = reg & 0xFE;