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

JavaKotlinBitwise OperatorsBitwise AndBitwise Or

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

You have named functions for them.

Directly from Kotlin docs

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

for example:

val x = (1 shl 2) and 0x000FF000

Here is the complete list of bitwise operations:

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

Solution 2 - Java

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

Solution 3 - Java

This is currently not supported, but most probably will be by the new Kotlin compiler K2, see Roman Elizarov's comment on the YouTrack issue KT-1440.

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

Solution 4 - Java

Another example:

Java:

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

Kotlin

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWater Magical View Question on Stackoverflow
Solution 1 - JavaSuresh AttaView Answer on Stackoverflow
Solution 2 - JavaAli FarisView Answer on Stackoverflow
Solution 3 - JavaCorbieView Answer on Stackoverflow
Solution 4 - JavafvaldiviaView Answer on Stackoverflow