Bitwise Operators
There are four bitwise operators (besides the shift operators):
symbol |
meaning |
~ |
NOT (or 1's compliment) |
& |
AND |
| |
OR |
^ |
XOR |
These operators can only be applied to integer expressions. The result
is on a bit by bit basis. Thus if an "int" has a size of 2 bytes or
16 bits, then the result is for the operation to be applied to each
corresponding pair of bits. The result for bit 0 is the operation
applied to bit 0 of both operands, while the result for bit 3 is the
operation applied to bit 3 of each of the operands - all independently.
The results of the four operations is as shown in 4 small truth tables
(as they are called) for all possible inputs of single bits:
|
AND
x | y | x&y |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
|
|
XOR
x | y | x^y |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
|
As a full example, if two integer variables 'a' and 'b' have the values
100 and 69 respectively and we perform an AND, then the result is:
expression | decimal | binary |
a | 100 | 0000 0000 0110 0100 |
b | 69 | 0000 0000 0100 0101 |
a&b | 69 | 0000 0000 0100 0100 |
The spaces in the binary representation are just for clarity.
© 1991-2008 Prem Sobel. All Rights Reserved.