Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert shift right (Java's >>) to Kotlin

Tags:

java

kotlin

I want to konvert java's code to Kotlin:

private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}

and I get:

private fun appendHex(sb: StringBuffer, b: Byte) {
    sb.append(hex.toCharArray()[b shr 4 and 0x0f]).append(hex.toCharArray()[b and 0x0f])
}

But Kotlin's standard shr expects Int as a first argument (not Byte). The same problem with and operator.

How to convert it to Kotlin?

like image 600
Rainmaker Avatar asked Mar 10 '18 11:03

Rainmaker


1 Answers

Bitwise operations like and, or, and shl are only defined for Int and Long in Kotlin. (https://kotlinlang.org/docs/reference/basic-types.html)

Just create extension functions that take Byte values.

private fun appendHex(sb: StringBuffer, b: Byte) {
    sb.append(hex.toCharArray()[b shr 4 and 0x0f]).append(hex.toCharArray()[b and 0x0f])
}

infix fun Byte.shl(that: Int): Int = this.toInt().shl(that)
infix fun Int.shl(that: Byte): Int = this.shl(that.toInt()) // Not necessary in this case because no there's (Int shl Byte)
infix fun Byte.shl(that: Byte): Int = this.toInt().shl(that.toInt()) // Not necessary in this case because no there's (Byte shl Byte)

infix fun Byte.and(that: Int): Int = this.toInt().and(that)
infix fun Int.and(that: Byte): Int = this.and(that.toInt()) // Not necessary in this case because no there's (Int and Byte)
infix fun Byte.and(that: Byte): Int = this.toInt().and(that.toInt()) // Not necessary in this case because no there's (Byte and Byte)

I used infix to use the operations like 1 shl 2 (as opposed to 1.shl(2)). (https://kotlinlang.org/docs/reference/functions.html)


Or simply, just add .toInt() to every expressions that use shl or and.

private fun appendHex(sb: StringBuffer, b: Byte) {
    sb.append(hex.toCharArray()[b.toInt() shr 4 and 0x0f]).append(hex.toCharArray()[b.toInt() and 0x0f])
}


Caution: In Java, << has higher operator precedence than &. In Kotlin, shl and and have the same operator precedence because they are both infix functions.
like image 136
Naetmul Avatar answered Oct 22 '22 02:10

Naetmul