A common use for the bitwise operators is to combine several values in a single variable for efficiency. For instance, a program with several "flag" variables, which always have a value of either 1 or 0 (representing true or false states), would normally require eight bits of memory each. The storage of a single digit only requires a single bit, however, so up to eight flags can be combined in a single variable, as seen with the "state" variable in this example:
Code:
#include <stdio.h>
#define FLAG_1 1 /* 0000 0001 */
#define FLAG_2 2 /* 0000 0010 */
#define FLAG_3 4 /* 0000 0100 */
#define FLAG_4 8 /* 0000 1000 */
#define FLAG_5 16 /* 0001 0000 */
#define FLAG_6 32 /* 0010 0000 */
#define FLAG_7 64 /* 0100 0000 */
#define FLAG_8 128 /* 1000 0000 */
int main()
{
int state = 44; /* 0010 1100 */
if ((state & FLAG_1) > 0) printf("Flag 1 is set\n");
if ((state & FLAG_2) > 0) printf("Flag 2 is set\n");
if ((state & FLAG_3) > 0) printf("Flag 3 is set\n");
if ((state & FLAG_4) > 0) printf("Flag 4 is set\n");
if ((state & FLAG_5) > 0) printf("Flag 5 is set\n");
if ((state & FLAG_6) > 0) printf("Flag 6 is set\n");
if ((state & FLAG_7) > 0) printf("Flag 7 is set\n");
if ((state & FLAG_8) > 0) printf("Flag 8 is set\n");
return 0;
}