# Lesson 7.5. Bit masking, how to check a single bit in C?

It is often necessary to test the status of a single bit. The problem is then to test this bit independently of the others. This page explains how to properly test a single bit isolated from the rest of a binary word.

## How it works?

The principle consists in forcing to zero all the bits except the one you want to test.

Clearing bits to zero is done thanks to a bitwise AND between the register and a mask. The bits of the mask are defined such as:

• 0 in the mask => all bits to inhibit ;
• 1 in the mask => the bit to check.

Suppose we want to test the most significant bits of an 8-bit word. The mask is:

$$mask = (1000~0000)_2 = (80)_{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 & 0 & 0 & 0 & \, & 0 & 0 & 0 & 0 & <= & mask \\ \hline b_7 & 0 & 0 & 0 & \, & 0 & 0 & 0 & 0 & <= & result \end{array}$$

By analyzing the result of equation 2, we easily understand that the result can only take two values :

• either $$b_7$$ equals 0 and the result is 0
• either $$b_7$$ equals 1 and the result is 0x80

To determine the status of the bit, we just need to test the masking result.

if ( (registre & 0x80) == 0x80) {
// The most significant bit is 1
// ...
}
else {
// The most significant bit is 0
// ...
}

The result of the bit-masking can only return 2 values: 0x80 and 0. From a purely logical point of view:

• 0x80 is the logical proposition TRUE ;
• 0 is the logical proposition FALSE.

The test of the above code can be simplified:

if ( registre & 0x80 ) {
// The most significant bit is 1
// ...
}
else {
// The most significant bit is 0
// ...
}

## Wait for a bit change

In embedded systems, it is often necessary to wait for the change of state of a bit. For example, pressing a button. This can be done on the same principle in a loop:

// Waits for the second least significant bit to change to 1
while !(PORTA & 0x02);

On the same principle, we can also expect a rising front:

// Waits for a rising edge on the second least significant bit
while (PORTA & 0x02);   // Waits for the bit to be 1
while !(PORTA & 0x02);  // Waits for the bit to change to 0

## Exercise

Write a program that asks the user to enter an integer. The program then displays the parity of the number entered. The program must use bit-masking to test the least significant bit.

• Least significant bit equals 0 => even number.
• Least significant bit equals 1 => odd number.
unsigned int N;
printf ("Enter a positive integer ");
scanf("%d", &N);

// Check the least significant bit
// to display parity
// COMPLETE HERE

## Quiz

How to proceed to test a bit independently of the others?

Which tests will be true if the third most significant bit of reg is 1?

Which tests will be true if the third most significant bit of reg is 0?

Which loops wait for the least significant bit of reg to go to 0?