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.

We might define our settings value like this...

unsigned char MODE;

Each individual setting (or "switch") might be defined in a .h file enumerating the powers of 2 like this...

#define ALL_OFF 0
#define SWITCH_1 1
#define SWITCH_2 2
#define SWITCH_3 4
#define SWITCH_4 8
#define SWITCH_5 16
#define SWITCH_6 32

At startup, we might initialize all of our machine's switches to the off position like this...


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...


If we need to check the current setting of an individual switch say, switch 3, we could use the bitwise AND operator ('&') like this...


printf("Switch 3 is on\n");
printf("Switch 3 is off\n");

(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...

To turn a switch OFF we can use the bitwise AND ('&') operator with the 1's compliment (~inverse) of the SWITCH_NUMBER ("mask") as shown in the following illustration...


Another Reference this link added 1/17/2014

Text and Graphics © 2003 - Mike McCarthy -