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:
Let's assume an 8-bit register named PORTA
that drives leds.
Nous supposerons que ce registre est accessible en lecture et en écriture.
Voici quelques exemples d'écritures dans le registre :
PORTA = 0x00;
turns off all ledsPORTA = 0x01;
turns on the led 0PORTA = 0x08;
turns on the led 1PORTA = 0x0F;
turns on the 4 leds on the rightPORTA = 0xFF;
turns on all ledsAssume 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;
Modify the program in the example above to set bit 6 to 0 instead of the bit 2.
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;
mask
used for bit masking.
Try again...