如何在 Kotlin 中使用 Java 的按位运算符?

How do I use Java's bitwise operators in Kotlin?

Java 有 binary-or |binary-and & 运算符:

int a = 5 | 10;
int b = 5 & 10;

它们似乎在 Kotlin 中不起作用:

val a = 5 | 10;
val b = 5 & 10;

如何在 Kotlin 中使用 Java 的按位运算符?

您已经为它们命名了函数。

直接来自Kotlin docs

Bitwise operations are represented by functions that can be called in infix form. They can be applied only to Int and Long.

例如:

val x = (1 shl 2) and 0x000FF000

这是按位运算的完整列表:

shl(bits) – signed shift left (Java's <<)
shr(bits) – signed shift right (Java's >>)
ushr(bits) – unsigned shift right (Java's >>>)
and(bits) – bitwise and
or(bits) – bitwise or
xor(bits) – bitwise xor
inv() – bitwise inversion

你可以在 Kotlin 中做到这一点

val a = 5 or 10;
val b = 5 and 10;

这里是您可以使用的操作列表

shl(bits) – signed shift left (Java's <<)
shr(bits) – signed shift right (Java's >>)
ushr(bits) – unsigned shift right (Java's >>>)
and(bits) – bitwise and
or(bits) – bitwise or
xor(bits) – bitwise xor
inv() – bitwise inversion

这目前不受支持,但很可能会被新的 Kotlin 编译器 K2 支持,请参阅 Roman Elizarov's comment on the YouTrack issue KT-1440

KT-46756 for the upcoming alpha release and keep an eye on the roadmap

另一个例子:

Java:

 byte dataHigh = (byte) ((data[byteOffset] & 0xF0) >> 4);

科特林

val d = (data[byteOffset] and 0xF0.toByte())
val dataHigh = (d.toInt() shr 4).toByte()