将右移(Java'>>)转换为Kotlin

时间:2018-03-10 11:04:23

标签: java kotlin

我想将Java的代码转换为Kotlin:

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

我得到了:

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

但Kotlin的标准shr期望Int作为第一个参数(不是Byte)。与and运算符相同的问题。

如何将其转换为Kotlin?

1 个答案:

答案 0 :(得分:2)

andorshl等按位操作仅在Kotlin中为IntLong定义。 (https://kotlinlang.org/docs/reference/basic-types.html

只需创建Byte值的extension functions

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)

我使用infix来使用1 shl 2之类的操作(而不是1.shl(2))。 (https://kotlinlang.org/docs/reference/functions.html

或者,只需将.toInt()添加到使用shland的每个表达式。

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

<小时/> 警告:在Java中,<<的运算符优先级高于&。在Kotlin中,shland具有相同的运算符优先级,因为它们都是中缀函数