Lesson 7.1. Bit masking

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.

Example of a register driving LEDs

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

Voici quelques exemples d'écritures dans le registre :

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:

General principle of bit masking

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?

Check Bravo! Bit masking is for modifying a bit while preserving the others. Try again...

What are the basic types of bit masking?

Check Bravo! The copy of a bit is possible, but it results from several masking operations. Try again...

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

reg = reg & 0xFE;
Check Bravo! We frequently find codes with a variable named mask used for bit masking. Try again...

See also


Last update : 11/22/2022