Mauerer app03.tex V1 - 09/04/2008 6:11pm Page 1205
Appendix C: Notes on C
As expected, the program produces the following output:
wolfgang@meitner>./bitmask
Bit 5 in val2 is set
It is, of course, possible to mask out not just one but several bits of a number by designing an appropriate
mask. If, for example, the last 5 bits of a number are to be analyzed, a mask can be designed in which the
first bit is moved to position 6 and then 1 is subtracted from the resulting number.
Bit position numbering begins at 0 as usual. Thebits at positions 0 to 5 are equal to 1 as a result of
subtraction, while the bits at positions 6 to 31 are equal to 0.
The desired bits in a bit string can be selected by ANDing as shown here:
int main() {
unsigned int val = 49;
unsigned int res;
unsigned int mask = 1;
mask <<= 5;
mask -= 1; printf("mask: %u\n", mask);
res = val & mask;
printf("val, res: %u, %u\n", val, res);
}
The program generates the following output:
wolfgang@meitner>./maskfive
mask: 31
val, res: 49, 17
A common programming error occurs when the operators&&(logical AND) and&
(bitwise AND) are confused. Because the former checks only whether both
arguments are greater than 0 and the latter performs a bitwise comparison, they
return different results.
The following example illustrates the difference between both operations:
int main() {
int val1 = 4;
int val2 = 8;
if (val1 & val2) {
printf("And\n");
}
if (val1 && val2) {
printf("And and\n");
}
}