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:

NOT
x~x
01
11
AND
xyx&y
000
010
100
111
OR
xyx|y
000
011
101
111
XOR
xyx^y
000
011
101
110

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:

expressiondecimalbinary
a1000000 0000 0110 0100
b690000 0000 0100 0101
a&b690000 0000 0100 0100

The spaces in the binary representation are just for clarity.


© 1991-2008 Prem Sobel. All Rights Reserved.