Lesson 7.2. Bit masking, how to clear a bit in C?

Clearing a bit while keeping the other is an elementary bit masking operation.

Bit masking in C, how to clear a bit with a bitwise and

How it works?

Clearing a bit is done with a bitwise AND between the initial register and a mask. The bits of the mask are defined as :

Let's suppose that we want to clear the 4 least significant bits of an 8 bits word. The mask is:

$$ mask = (1111~0000)_2 = (F0)_{16} $$

$$ \begin{array}[t]{r} b_7 & b_6 & b_5 & b_4 & \, & b_3 & b_2 & b_1 & b_0 & <= & initial \: word \\ \& \quad 1 & 1 & 1 & 1 & \, & 0 & 0 & 0 & 0 & <= & mask \\ \hline b_7 & b_6 & b_5 & b_4 & \, & 0 & 0 & 0 & 0 & <= & result \end{array} $$

This principle is based on the following relations of Boolean algebra:

The mask in this example can be applied to the variable reg with the following statement:

result = reg & 0xF0;

If the initial data is overwritten by masking, the instruction can be synthesized using a combined affection operator:

reg &= 0xF0;

Exercise 1

Complete the program below to clear the least significant bit of the variable reg to zero:

// | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 |
unsigned char reg = 0xA3;
printf("Before : ");
affBin(reg);

// Clear the least significant bit
// COMPLETE HERE

// Display the result
printf("After  : ");
affBin(reg); 

Exercise 2

Complete the program below to clear the 3 most significant bits of the variable reg :

// | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 |
unsigned char reg = 0xA3;
printf("Before : ");
affBin(reg);

// Clear the 3 most significant bits
// COMPLETE HERE

// Display the result
printf("After  : ");
affBin(reg); 

Quiz

What operator should be used to clear a bit?

Check Bravo! Clearing a bit is done with a bitwise AND. Try again...

When clearing a bit with a bitwise AND and a mask, a bit set to 1 in the mask will...

Check Bravo! The one bits of the mask keep initial bits, because in Boolean logic: \( x · 1 = x \). Try again...

When clearing a bit with a bitwise AND and a mask, a bit set to 0 in the mask will...

Check Bravo! The zero bits of the mask force to zero, because in Boolean logic: \( x · 0 = 0 \). Try again...

What is reg after these instructions?

reg = 0xAA;
reg &= 0x0F;
Check Bravo! The mask clears the 4 most significant bits. Try again...

See also


Last update : 11/22/2022