77

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?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Water Magical
  • 979
  • 1
  • 9
  • 13

4 Answers4

96

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
Marcono1234
  • 5,856
  • 1
  • 25
  • 43
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 11
    Note that bitwise inversion would be used like `5.inv()`, not as infix like the others – xjcl Nov 22 '20 at 15:15
  • 2
    Note that bitwise inversion is also known as bitwise complement or bitwise NOT – grian Jan 15 '21 at 09:02
  • 3
    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. – Hakanai Jul 26 '21 at 00:04
  • 1
    @Hakanai hard agree. It was especially hard for me when coming over from a language like python where I was accustomed to writing expressions like `if (condition1 or condition2) and condition3: do this`. This is much more intuitive and just naturally easy to understand. – Anchith Acharya Jun 22 '23 at 09:51
25

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
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
1

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.

Corbie
  • 819
  • 9
  • 31
0

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()
fvaldivia
  • 446
  • 5
  • 13