官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 建昌县| 兴国县| 阜平县| 渝中区| 环江| 马关县| 上杭县| 临猗县| 乳源| 黔江区| 偏关县| 炎陵县| 丹棱县| 荆州市| 象山县| 中宁县| 改则县| 安福县| 尉犁县| 左贡县| 定安县| 襄汾县| 南平市| 沙洋县| 云林县| 景德镇市| 昌宁县| 盐山县| 武夷山市| 陇川县| 介休市| 常熟市| 华容县| 渭源县| 顺义区| 革吉县| 洛扎县| 永川市| 平顶山市| 丁青县| 清镇市|