Bit-Wise Operators
Objective #1: Use bit-wise operators
- | is the bit-wise OR operator
- & is the bit-wide AND operator
- ^ is the bit-wise XOR (i.e. exclusive or) operator. Given 2 binary operands, the ^ operation results in 1 (true) when exactly one operand is 1 (true) and the other is 0 (false). For example, if a = 26, which is
11010 in binary, and b = 9, which is 01001 in binary, then a ^ b evaluates
to 19, which is 10011 in binary. The 1s in the result represent places
where a and b "differ" in their binary representations. You can also
think of it as "add without carry". This is like the symmetric
difference set operation in mathematics, and has many uses in computing,
such as bit flipping, setting a variable to zero, and checking for signed arithmetic overflow. It is, like the other bitwise operations (&,
| , ! ,>>,<<), very efficient because it maps to a low level machine
operation (xor).
- http://en.wikipedia.org/wiki/Bitwise_operation#XOR
- Example:
cout << 22^13;
displays the value 27 because
1 0 1 1 0 (22 in base 2)
^ ^ ^ ^ ^
0 1 1 0 1 (13 in base 2)
= = = = =
1 1 0 1 1 (27 in base 2)