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);  
#include <stdio.h>

// Display x in binary
void affBin(unsigned char x);

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

    // Set b0 and b1 (mask 0000 0011)
    reg |= 0x03;

    // Clear b2 and b3 (mask 1111 0011)
    reg &= 0xF3;

    // Toggle b4 and b5 (mask 0011 0000)
    reg ^= 0x30;

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

    return 0;
}

// Display x in binary
void affBin(unsigned char x) {
    for (int i = sizeof(x) << 3; i; i--)
        putchar('0' + ((x >> (i - 1)) & 1));
    putchar('\n');
}

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);  
#include <stdio.h>

// Display x in binary
void affBin(unsigned char x);

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

    // Clear the 4 least significant bits (mask 1111 0000)
    reg &= 0xF0;

    // Set the 4 most significant bits (mask 1111 0000)
    reg |= 0xF0;

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

    return 0;
}

// Display x in binary
void affBin(unsigned char x) {
    for (int i = sizeof(x) << 3; i; i--)
        putchar('0' + ((x >> (i - 1)) & 1));
    putchar('\n');
}

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 : 11/30/2026