Converting a byte array into a hex string
As I am on Kotlin 1.3 you may also be interested in the UByte
soon (note that it's an experimental feature. See also Kotlin 1.3M1 and 1.3M2 announcement)
E.g.:
@ExperimentalUnsignedTypes // just to make it clear that the experimental unsigned types are usedfun ByteArray.toHexString() = asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') }
The formatting option is probably the nicest other variant (but maybe not that easily readable... and I always forget how it works, so it is definitely not so easy to remember (for me :-)):
fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }
This question has been answered, but I did not like the formatting. Here is something that formats it into something more readable ... at least for me.
@JvmOverloadsfun ByteArray.toHexString(separator: CharSequence = " ", prefix: CharSequence = "[", postfix: CharSequence = "]") = this.joinToString(separator, prefix, postfix) { String.format("0x%02X", it) }
output:
[0x10 0x22]