- 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.
推薦閱讀
- Learning ASP.NET Core 2.0
- Programming ArcGIS 10.1 with Python Cookbook
- NumPy Essentials
- 精通Scrapy網絡爬蟲
- Mastering Drupal 8 Views
- INSTANT Passbook App Development for iOS How-to
- Linux Device Drivers Development
- .NET 3.5編程
- Python之光:Python編程入門與實戰
- Scala Data Analysis Cookbook
- C語言程序設計與應用(第2版)
- Hands-On JavaScript for Python Developers
- Java 9 Programming By Example
- Arduino電子設計實戰指南:零基礎篇
- 算法秘籍