Lesson 7.6. Overview of bit masking

The table below summarizes the three types of masking:

Description Operator C operator 0 in the mask 1 in the mask
Forçage à zéro bitwise AND & Clear the bit Keep the bit
Forçage à un bitwise OR | Keep the bit Set the bit
Inversion de bits bitwise XOR ^ Keep bit Toogle the bit

Exercise 1

$$ reg = ( b_7 \: b_6 \: b_5 \: b_4 \; b_3 \: b_2 \: b_1 \: b_0 )_2 $$

Complete the program below to:

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

// Set b0 and b1
// COMPLETE HERE

// Clear b2 and b3
// COMPLETE HERE

// Toggle b4 and b5
// COMPLETE HERE

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

Exercise 2

Complete the program below to:

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

// Clear the 4 least significant bits and set the 4 least significant bits.
// COMPLETE HERE

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

Quiz

What operator should be used to invert some bits while keeping the others?

Check Bravo! The masking to invert bits is done with a bitwise exclusive OR. Try again...

What operator should be used to clear a bit?

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

What operator should be used to set a bit?

Check Bravo! Setting a bit is done with a bitwise OR. Try again...

Which instructions clears the 8 bits?

Check Bravo! There is no need to use bit-masking to change all the bits. An assignment is more suitable. Try again...

See also


Last update : 10/24/2023