Lesson 7.4. Bit masking, how to toggle a bit in C?

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

Bit masking in C, how to toggle a bit with a bitwise XOR

How it works?

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

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

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

$$ \begin{array}[t]{r} b_7 & b_6 & b_5 & b_4 & \, & b_3 & b_2 & b_1 & b_0 & <= & initial \: word \\ + \quad 0 & 0 & 0 & 0 & \, & 1 & 1 & 1 & 1 & <= & mask \\ \hline b_7 & b_6 & b_5 & b_4 & \, & \overline{b_3} & \overline{b_2} & \overline{b_1} & \overline{b_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 ^ 0x0F;

Exercise 1

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

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

// Toggle the least significant bit
// COMPLETE HERE

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

Exercise 2

Complete the program below to toggle the 4 most significant bits of the variable reg :

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

// Toggle the 4 least significant bit
// COMPLETE HERE

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

Quiz

What operator should be used to toggle a bit?

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

When setting a bit with a bitwise XOR and a mask, a bit set to 1 in the mask will...

Check Bravo! The one bits of the mask toggle the bits, because in Boolean logic: \( x \oplus 1 = \overline{x} \). Try again...

When toggling a bit with a bitwise XOR and a mask, a bit set to 0 in the mask will...

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

What is reg after these instructions?

reg = 0xAA;
reg ^= 0x0F;
Check Bravo! The mask toggle the 4 least significant bits. Try again...

See also


Last update : 11/22/2022