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 used
fun 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) }
printf
does what we want here:
fun ByteArray.toHexString() : String {
return this.joinToString("") {
java.lang.String.format("%02x", it)
}
}