Bit strings and bitwise operators are often used to make masks. A
mask is a bit string that "fits over" another bit string and produces
a desired result, such as singling out particular bits from the second
bit string, when the two bit strings are operated upon. This is
particularly useful for handling flags; programmers often wish to know
whether one particular flag is set in a bit string, but may not care
about the others. For example, you might create a mask that only allows
the flag of interest to have a non-zero value, then AND that mask with
the bit string containing the flag.
Consider the following mask, and two bit strings from which we want to
extract the final bit:
The zeros in the mask mask off the first seven bits and only let
the last bit show through. (In the case of the first value, the last bit is 1;
in the case of the second value, the last bit is 0.)
Alternatively, masks can be built up by operating on several flags, usually
with inclusive OR:
See Opening files at a low level, for a code example that actually
uses bitwise OR to join together several flags.
It should be emphasized that the flag and mask examples are written
in pseudo-code, that is, a means of expressing information
that resembles source code, but cannot be compiled. It is not possible to
use binary numbers directly in C.
The following code example shows how bit masks and bit-shifts can be combined.
It accepts a decimal number from the user between 0 and 128, and prints out
a binary number in response.
#include <stdio.h>
#define NUM_OF_BITS 8
/* To shorten example, not using argp */
int main ()
{
char *my_string;
int input_int, args_assigned;
int nbytes = 100;
short my_short, bit;
int idx;
/* This hex number is the same as binary 10000000 */
short MASK = 0x80;
args_assigned = 0;
input_int = -1;
while ((args_assigned != 1) ||
(input_int < 0) || (input_int > 128))
{
puts ("Please enter an integer from 0 to 128.");
my_string = (char *) malloc (nbytes + 1);
getline (&my_string, &nbytes, stdin);
args_assigned = sscanf (my_string, "%d", &input_int);
if ((args_assigned != 1) ||
(input_int < 0) || (input_int > 128))
puts ("\nInput invalid!");
}
my_short = (short) input_int;
printf ("Binary value = ");
/*
Convert decimal numbers into binary
Keep shifting my_short by one to the left
and test the highest bit. This does
NOT preserve the value of my_short!
*/
for (idx = 0; idx < NUM_OF_BITS; idx++)
{
bit = my_short & MASK;
printf ("%d", bit/MASK);
my_short <<= 1;
}
printf ("\n");
return 0;
}