Programming and Graphics

(Kiana) #1

3.9 Bitwise operators 87


Bitwise operator Binary operation

<< left shift
>> right shift
& and
| or
^ xor (exclusive or)
~ not

Table 3.9.1Bitwise operators in C++. When operating on a number, these
operators produce a new number with altered bits.


a = 50 0000000000110010
b=a<<3 = 400 0000000110010000
c=a&b=16 0000000000010000

Evidently, the operationa&bproduces a number whoseith binary digit is 1
only if the corresponding binary digits ofaandbare both 1, and 0 otherwise.
Accordingly, & is theandbitwise operator.


“or” and “xor” operators


The “or” operationa|bproduces a number whoseith binary digit is 1
only if at least one of the correspondingith binary digits ofaandbis 1, and 0
otherwise.


The “exclusive or” operationa^bproduces a number whoseith binary
digit is 1 if the corresponding binary digits ofaandbare different, and 0
otherwise.


“not” operator


Thenotoperator~aproduces a number whoseith binary digit is 0 if the
corresponding digit ofais 1, and vice versa.


Applications


Table 3.9.1 summarizes the bitwise operators. In practice, these opera-
tors are commonly used for packing multiple values into one integer and thus
compressing a file. This is done by shifting withandto extract values, and
usingxorto add values.

Free download pdf