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

霸气de小男生 提交于 2020-05-25 09:01:48

问题


Java has binary-or | and binary-and & operators:

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

They do not seem to work in Kotlin:

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

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


回答1:


You have named functions for them.

Directly from Kotlin docs

As of bitwise operations, there're no special characters for them, but just named functions that can be called in infix form.

for example:

val x = (1 shl 2) and 0x000FF000

Here is the complete list of bitwise operations (available for Int and Long only):

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



回答2:


you can do this in Kotlin

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

here list of operations that you can use

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


来源:https://stackoverflow.com/questions/48474520/how-do-i-use-javas-bitwise-operators-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!