Software bitwise operations are often used to control a virtual
or real machine with a group of settings that can be switched on
or off. The entire group of settings may be represented in a
single unsigned integer type.
The illustrations below use an 8-bit type such as an unsigned char. Using such an 8-bit type would accommodate a machine whose "states" could range from 0 - 255.
During the course of the program various switches can be turned on
or off by manipulating the MODE with bitwise operations.
For example, if we wanted to turn switches 1, 3 and 5 ON, we could
use the bitwise OR operator ('|') like this...
RESULT = MODE & SWITCH_3;
if(RESULT == SWITCH_3)
(The illustrations use "state" and "mask" in place of our program's variables MODE and SWITCH_NUMBER. An additional variable RESULT might be used to trap the result of the bitwise operation.)
In the example above, the '&' (AND) operator accumulates powers of 2 in the RESULT variable only where BOTH the MODE AND the SWITCH_NUMBER are ON (both 1's). The bitmask itself (SWITCH_NUMBER) will be filtered down to the RESULT only if that setting was already on. Therefore if the RESULT is equal to the "mask" (SWITCH_NUMBER), that switch is on, otherwise it is off.
To turn a switch ON we can use the bitwise OR ('|') operator as shown in the following illustration...