I don't know if somebody has already answered this question. If it's the case, then, please for the redondancy.
I would like to transform this function into Kotlin function. Thanks for the help.
private final static String HEX = "XXXXXXXXX";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
I suggest using an extension function for that:
private const val HEX = "XXXXXXXXX"
fun StringBuffer.appendHex(b: Byte): StringBuffer {
val i = b.toInt()
append(HEX[i shr 4 and 0x0f])
append(HEX[i and 0x0f])
return this
}
I also made the function return this
again so you can even call it in a chain:
myStringBuffer
.append(someThing)
.appendHex(myByte)
.append(someThingElse)
If it's just a hex string representation you need (and that's also what I get from your comment), you may just want to use the following instead:
fun StringBuffer.appendHex(b : Byte) = append("%02X".format(b))
Usage is then the same as also Lino has shown:
StringBuffer()
.append("some text")
.appendHex(someByte)
or if you need to keep your current signature:
companion object {
@JvmStatic
fun appendHex(s : StringBuffer, b : Byte) {
s.append("%02X".format(b))
}
}
companion object {
private const val HEX = "XXXXXXXXX"
@JvmStatic
private fun appendHex(sb: StringBuffer, b: Int) {
sb.append(HEX[b shr 4 and 0x0f]).append(HEX[b and 0x0f])
}
}
Please note that I had to change the Byte
to Int
, because Byte
doesn't seem to have shr
and and
defined for some unknown reason.
No, I really don't know why bitwise operators would not be defined over byte .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.