What’s Next 775
21
set every bit that is clear, and clear every bit that is set (0111 1111). When you AND
these numbers, the original number is unchanged, except for the eighth bit, which is
forced to zero.
1010 0110 1010 0110 // bit 8 is set
& 1111 1111 0111 1111 // ~128
1010 0110 0010 0110 // bit 8 cleared
To fully understand this solution, do the math yourself. Each time both bits are 1, write 1
in the answer. If either bit is 0, write 0 in the answer. Compare the answer with the origi-
nal number. It should be the same except that bit 8 was cleared.
Flipping Bits ..................................................................................................
Finally, if you want to flip bit 8, no matter what its state, you exclusive OR the number
with 128. If you do this twice, you end up back with the original setting. Thus,
1010 0110 1010 0110 // number
^ 0000 0000 1000 0000 // 128
1010 0110 0010 0110 // bit flipped
^ 0000 0000 1000 0000 // 128
1010 0110 1010 0110 // flipped back
DOset bits by using masks and the OR
operator.
DOclear bits by using masks and the
AND operator.
DOflip bits using masks and the exclu-
sive OR operator.
DON’T confuse the different bit opera-
tors.
DON’T forget to consider bits to the left
of the bit(s) you are flipping. One byte is
eight bits; you need to know how many
bytes are in the variable you are using.
DO DON’T
Bit Fields ........................................................................................................
Under some circumstances, every byte counts, and saving six or eight bytes in a class
can make all the difference. If your class or structure has a series of Boolean variables or
variables that can have only a very small number of possible values, you might save
some room using bit fields.
Using the standard C++ data types, the smallest type you can use in your class is a type
char, which might be just one byte. You will usually end up using an int, which is most