Bitwise operators are operators that work on a multi-bit value but conceptually one bit at a time.
- AND is 1 only if both of its inputs are 1.
- OR is 1 if one or more of its inputs are 1.
- XOR is 1 only if exactly one of its inputs are 1.
- NOT is 1 only if its input are 0.
These can be best described as truth tables. Inputs possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the two inputs.
AND | 0 1 OR | 0 1 XOR | 0 1 NOT | 0 1
----+----- ---+---- ----+---- ----+----
0 | 0 0 0 | 0 1 0 | 0 1 | 1 0
1 | 0 1 1 | 1 1 1 | 1 0
One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:
201: 1100 1001
AND 15: 0000 1111
------------------
IS 9 0000 1001
Another example is if you have two 4-bit values that you want to pack into an 8-bit one, you can use all three of your operators (left-shift
, and
and or
):
packed_val = ((val1 & 15) << 4) | (val2 & 15)
- The
& 15
operation will make sure that both values only have the lower 4 bits.
- The
<< 4
is a 4-bit shift left to move val1
into the top 4 bits of an 8-bit value.
- The
|
simply combines these two together.
If val1
is 7 and val2
is 4:
val1 val2
==== ====
& 15 (and) xxxx-0111 xxxx-0100 & 15
<< 4 (left) 0111-0000 |
| |
+-------+-------+
|
| (or) 0111-0100