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

22,785

Solution 1

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

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
Share:
22,785
Water Magical
Author by

Water Magical

Updated on July 05, 2022

Comments

  • Water Magical
    Water Magical almost 2 years

    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?

  • xjcl
    xjcl over 3 years
    Note that bitwise inversion would be used like 5.inv(), not as infix like the others
  • grian
    grian over 3 years
    Note that bitwise inversion is also known as bitwise complement or bitwise NOT
  • Hakanai
    Hakanai almost 3 years
    I find it odd that Kotlin decided bitwise operators would get these awkwardly named functions, while the actual boolean operators like and and or still got operators. It's a bit backwards isn't it? If anything I'd want these to stay as the symbols and the boolean operators to become words.