- Learning Scala Programming
- Vikash Sharma
- 184字
- 2025-04-04 17:32:11
Bitwise operators
We can perform operations on individual bits of Integer types using Bitwise operators. These includes Bitwise AND (&), OR (|), and XOR (^):
scala> 1 & 2
res2: Int = 0
scala> 1 | 2
res3: Int = 3
scala> 1 ^ 2
res5: Int = 3
These operators can be performed only on Int. If you try this on Double, it'll throw an error: value & is not a member of Double. These operators perform operations on individual bits; in our case, 1 is converted into bits as 01 and 2 as 10, and then AND, OR, and XOR operations are performed:
- 0001 AND 0010 resulted into 00 means 0
- 0001 OR 0010 resulted into 11 means 3
- 0001 XOR 0010 resulted into 11 means 3
We can perform a logical not-operating using ~ operator:
scala> ~2
res8: Int = -3
There are also three shift methods for Int types named shift right (>>), shift left (<<) and unsigned-shift right (>>>). These are binary operators working on two operands. Bits of operand on the left are shifted by value to the right.