Bitwise operations work at the bit level, i.e. the individual "digits" of a byte.
One of the functions of bitwise operators is to work with bitflags like the flags used with std::cout and std::cin.
Bitwise operators (examples are not in the C++ variable format):
-AND (&)
This returns a bitwise 1 if and only if the two bits being compared are both 1.
Useful for finding if a bitflag is set.
3 & 2
0 0 1 1
& 0 0 1 0
-----------
0 0 1 0
--> 3 & 2 == 2
|
-OR (|)
This returns a bitwise 1 if and only if at least one of the bits being compared is 1.
Good for switching on a bitflag while leaving the others untouched.
3 | 2
0 0 1 1
| 0 0 1 0
-----------
0 0 1 1
--> 3 | 2 == 3
|
-Complement (~)
This reverses the bit.
~127
~ 0 1 1 1 1 1 1 1
---------------------
1 0 0 0 0 0 0 0
--> ~127 == 128
|
-XOR (^)
Exclusive-or returns a bitwise 1 if and only if the two bits being compared are different.
Useful for switching a bitflag to either state while leaving the rest untouched.
3 ^ 2
0 0 1 1
^ 0 0 1 0
-----------
0 0 0 1
--> 3 ^ 2 == 1
|
-Left shift (<<)
This shifts all bits one digit to the left, effectively multiplying the integer by two. The number of times the bits are shifted is determined by the second parameter.
3 << 2
0 0 1 1
<< 2
-----------
1 1 0 0
--> 3 << 2 == 12 == 3*2*2
|
-Right shift (>>)
This shifts all bits one digit to the right, effectively dividing the integer by two. The number of times the bits are shifted is determined by the second parameter.
7 >> 2
0 1 1 1
>> 2
-----------
0 0 0 1
--> 7 >> 2 == 1 == 7/(2*2)
|
A good table I've found is:
operator &
0 & x = 0
1 & x = x
operator |
0 | x = x
1 | x = 1
operator ^
0 ^ x = x
1 ^ x = ~x
|