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

  • Learning Scala Programming
  • Vikash Sharma
  • 184字
  • 2021-06-30 19:07:52

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.

主站蜘蛛池模板: 耒阳市| 银川市| 类乌齐县| 固原市| 通州区| 论坛| 阿勒泰市| 河北省| 巧家县| 莱芜市| 兴城市| 苍山县| 云阳县| 保山市| 景洪市| 虹口区| 禹州市| 龙门县| 淮阳县| 天门市| 册亨县| 合肥市| 孟州市| 灵丘县| 福海县| 陆良县| 宣恩县| 云霄县| 饶阳县| 湟中县| 蓝山县| 大名县| 独山县| 桐乡市| 九江市| 鸡西市| 阿拉善盟| 木里| 九江县| 宝清县| 图们市|