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.
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 :
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
// ...
}
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
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.
unsigned int N;
printf ("Enter a positive integer ");
scanf("%d", &N);
// Check the least significant bit
// to display parity
// COMPLETE HERE
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?
if ( reg & 0x20 == 1)
if ( reg & 0x20 == 0x20)
if ( reg & 0x20 != 0)
0x20
, it can be done in different ways.
Try again...
Which tests will be true if the third most significant bit of reg
is 0?
if ( reg & 0x20 )
if ( reg & 0x20 == 0)
if ( reg & 0x20 == 0x20)
if ( !(reg & 0x20) )
Which loops wait for the least significant bit of reg
to go to 0?
while (reg & 0x01);
while !(reg & 0x01);
while (reg & 0x01 == 0);
while (reg & 0x01 != 0);