Bitwise Operators
- Integers (int and long) can be considered as collections of 32 or 64 bits.
- Bitwise operators perform logical operations on each bit position, where
1 is regarded as true and zero false.
- Bitwise and
(a & b)
- Result is 1 in every bit position where both operands have a 1.
- Bitwise or
(a | b)
- Result is 1 only in positions where one or both operands have a 1.
- Bitwise xor
(a ^ b)
- Result is 1 in positions where the two corresponding bits are different.
- Bitwise not
(~a)
- Unary operator. Result is each bit of operand inverted.
- Shift left
(a << n)
- Shifts bits n positions left. Zeros added on right.
- Shift right
(a >> n)
- Shifts bits n positions right. High-order bit inserted on left.
- Shift right
(a >>> n)
- Shifts bits n positions right. Zeros inserted at left.
- See Deitel&Deitel p 1117
Bitwise Operators - Exercises
- For the following examples, note that 3 is 0000...0011, 5 is 0000...0101,
and -1 is 1111...1111.
3 & 5 ____________________
3 | 5 ____________________
3 ^ 5 ____________________
~3 ____________________
5 << 2 ____________________
5 >> 2 ____________________
-1 >> 30 ____________________
-1 >>> 30 ____________________
Bitwise Operators - Uses
- Efficient storage.
- Status bits. Eg, Mouse event key mask.
- Eg, representing Connect-Four board.
- Packing or unpacking values into a single int/long.
- Efficient computation
- On some (esp old) machines, shifting is faster than multiplying or
dividing by powers of two.
- Problems
- How could you use bit operations to test whether a number is odd?
- How would you multiply by 256?
End