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

Rai*_*ker 5 java kotlin

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

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

我得到:

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

但是 Kotlin 的标准shr期望 Int 作为第一个参数(不是Byte)。and运营商同样的问题。

如何将其转换为 Kotlin?

Nae*_*mul 9

and, or, 和 之类的按位运算shl仅在 Kotlin 中为Int和定义Long。( https://kotlinlang.org/docs/reference/basic-types.html )

只需创建带值的扩展函数Byte

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)
Run Code Online (Sandbox Code Playgroud)

我曾经infix使用过像1 shl 2(而不是1.shl(2))这样的操作。( https://kotlinlang.org/docs/reference/functions.html )


或者简单地说,只需添加.toInt()到每个使用shlor 的表达式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])
}
Run Code Online (Sandbox Code Playgroud)


注意:在 Java 中,<<运算符优先级高于&. 在 Kotlin 中,shland具有相同的运算符优先级,因为它们都是中缀函数