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?
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
infix fun shl(bitCount: Int): Int. Shifts this value left by the bitCount number of bits. Note that only the five lowest-order bits of the bitCount are used as the shift distance. The shift distance actually used is therefore always in the range 0.. 31 .
Bitwise and bit shift operators are used on only two integral types (Int and Long) to perform bit-level operations. To peform these operations, Kotlin provides 7 functions using infix notation. 1. or The or function compares corresponding bits of two values.
Bitwise operators in Java. Bitwise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree. This operator is binary operator, denoted by ‘|’.
Kotlin supports the following operators and special symbols: +, -, *, /, % - mathematical operators. * is also used to pass an array to a vararg parameter. =. assignment operator. is used to specify default values for parameters. +=, -=, *=, /=, %= - augmented assignment operators. ++, -- - increment and decrement operators.
To peform these operations, Kotlin provides 7 functions using infix notation. The or function compares corresponding bits of two values. If either of the bits is 1, it gives 1. If not, it gives 0. For example, The and function compares corresponding bits of two values. If both bits are 1, it is evaluated to 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
andLong
.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With