Ben Chuanlong Du's Blog

It is never too late to learn.

Bitwise Operators in Kotlin

Comments

  1. When you use 1L shl 2, shl is considered as the left-shift operator instead of a method call.

  2. Bitwise operators are computed from left to the right.

  3. Bitwise operators have relatively low priority (lower than arithmatic operators), It is suggested that you use parentheses when you mix lower precendenc (bitwise opertors, ternary opertor, etc.) and high precendenc operators together. A even better approach in Kotlin is to avoid using bitwise operators and use the corresponding methods instead.

In [1]:
1L shl 2
Out[1]:
4
In [2]:
1L shl 2 xor 4
Out[2]:
0
In [4]:
1L shl 2 xor 4 xor 8
Out[4]:
8
In [ ]:

Precedence of Bitwise operators

Bitwise operators are computed from the left to the right.

In [1]:
1L shl 2
Out[1]:
4
In [2]:
1L shl 2 xor 4
Out[2]:
0
In [4]:
1L shl 2 xor 4 xor 8
Out[4]:
8
In [ ]:

Comments