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?
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])
}
<<
has higher operator precedence than &
. In Kotlin, shl
and and
have the same operator precedence because they are both infix functions.
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