Sams Teach Yourself C in 21 Days

(singke) #1
Working with Memory 585

20


Operation Example
AND 11110000
& 01010101
----------
01010000

Inclusive OR 11110000
| 01010101
----------
11110101
Exclusive OR 11110000
^ 01010101
----------
10100101

You just read that bitwise ANDand bitwise inclusive ORcan be used to clear or set,
respectively, specified bits in an integer value. Here’s what that means. Suppose you have
a type charvariable, and you want to ensure that the bits in positions 0 and 4 are cleared
(that is, equal to 0 ) and that the other bits stay at their original values. If you ANDthe
variable with a second value that has the binary value 11101110 , you’ll obtain the desired
result. Here’s how this works:
In each position where the second value has a 1 , the result will have the same value, 0 or
1 , as was present in that position in the original variable:
0 & 1 == 0
1 & 1 == 1
In each position where the second value has a 0 , the result will have a 0 regardless of the
value that was present in that position in the original variable:
0 & 0 == 0
1 & 0 == 0
Setting bits with ORworks in a similar way. In each position where the second value has
a 1 , the result will have a 1 , and in each position where the second value has a 0 , the
result will be unchanged:
0 | 1 == 1
1 | 1 == 1
0 | 0 == 0
1 | 0 == 1

32 448201x-CH20 8/13/02 11:16 AM Page 585

Free download pdf