Search code examples
javakotlinbitwise-operatorsbitwise-andbitwise-or

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


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?


Solution

  • 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