Operator OR ..................................................................................................
The second bitwise operator is OR (|). Again, this is a single vertical bar, in contrast to
the logical OR, which is two vertical bars. When you OR two bits, the result is 1 if either
bit is set or if both are. If neither bit is set, the value is 0.
Operator Exclusive OR ..................................................................................
The third bitwise operator is exclusive OR (^). When you exclusive OR two bits, the
result is 1 if the two bits are different. The result is 0 if both bits are the same—if both
bits are set or neither bit is set.
The Complement Operator ............................................................................
The complement operator (~) clears every bit in a number that is set and sets every bit
that is clear. If the current value of the number is 1010 0011, the complement of that
number is 0101 1100.
Setting Bits ....................................................................................................
When you want to set or clear a particular bit, you use masking operations. If you have a
four-byte flag and you want to set bit 8 so that it is true (on), you need to OR the flag
with the value 128.
Why? 128 is 1000 0000 in binary; thus, the value of the eighth bit is 128. Whatever the
current value of that bit (set or clear), if you OR it with the value 128 , you will set that
bit and not change any of the other bits. Assume that the current value of the eight bits is
1010 0110 0010 0110. ORing 128 to it looks like this:
9 8765 4321
1010 0110 0010 0110 // bit 8 is clear
| 0000 0000 1000 0000 // 128
_ _ _ _ _ _ _ _ _ _ _
1010 0110 1010 0110 // bit 8 is set
You should note a few more things. First, as usual, bits are counted from right to left.
Second, the value 128 is all zeros except for bit 8, the bit you want to set. Third, the
starting number 1010 0110 0010 0110 is left unchanged by the OR operation, except that
bit 8 was set. Had bit 8 already been set, it would have remained set, which is what you
want.
Clearing Bits ..................................................................................................
If you want to clear bit 8, you can AND the bit with the complement of 128. The com-
plement of 128 is the number you get when you take the bit pattern of 128 (1000 0000),
774 Day 21