What’s Next 773
21
Bit Twiddling ......................................................................................................
Often, you will want to set flags in your objects to keep track of the state of your object.
(Is it in AlarmState? Has this been initialized yet? Are you coming or going?)
You can do this with user-defined Booleans, but some applications—particularly those
with low-level drivers and hardware devices—require you to be able to use the individual
bits of a variable as flags.
Each byte has eight bits, so in a four-byte longyou can hold 32 separate flags. A bit is
said to be “set” if its value is 1 and clear if its value is 0. When you set a bit, you make
its value 1 , and when you clear it, you make its value 0. (Set and clear are both adjectives
and verbs.) You can set and clear bits by changing the value of the long, but that can be
tedious and confusing.
Appendix A, “Working with Numbers: Binary and Hexadecimal,”
provides valuable additional information about binary and hexadecimal
manipulation.
NOTE
C++ provides bitwise operators that act upon the individual bits of a variable. These look
like, but are different from, the logical operators, so many novice programmers confuse
them. The bitwise operators are presented in Table 21.1.
TABLE21.1 The Bitwise Operators
Symbol Operator
& AND
| OR
^ exclusive OR
~ complement
Operator AND ................................................................................................
The AND operator (&) is a single ampersand, in contrast to the logical AND, which is
two ampersands. When you AND two bits, the result is 1 if both bits are 1, but 0 if either
or both bits are 0. The way to think of this is the following: The result is 1 if bit 1 is set
and if bit 2 is set; otherwise, the result is 0.