Converting a byte array into a hex string
Solution 1
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) }
Solution 2
printf
does what we want here:
fun ByteArray.toHexString() : String {
return this.joinToString("") {
java.lang.String.format("%02x", it)
}
}
Solution 3
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.
@JvmOverloads
fun ByteArray.toHexString(separator: CharSequence = " ", prefix: CharSequence = "[", postfix: CharSequence = "]") =
this.joinToString(separator, prefix, postfix) {
String.format("0x%02X", it)
}
output:
[0x10 0x22]
Solution 4
fun ByteArray.toHexString() = joinToString("") {
Integer.toUnsignedString(java.lang.Byte.toUnsignedInt(it), 16).padStart(2, '0')
}
Fortunately, Java has toUnsignedString
methods on Integer
and Long
. UNfortunately, these methods are only on Integer
and Long
, so you need to convert each byte first (using Byte#toUnsignedInt
).
Raphael
I am a computer scientist by training, which means I now think like one: always analysing, abstracting, reducing, problem solving. In addition, I picked up some affection and, hopefully, ability for actually building software over the years. You can take a look over on Github. During my time at university I have found a passion for teaching, by which I mean helping people learn. Some say I was quite the nitpicker; it's for your best, I promise! In my free time I play games, read books, code, work out, enjoy music, and roam the webs. I maintain a gallery of sketches I created for posts on Stack Exchange.
Updated on May 08, 2020Comments
-
Raphael almost 4 years
Surprisingly (to me), this code does not do what I want:
fun ByteArray.toHexString() : String { return this.joinToString("") { it.toString(16) } }
Turns out
Byte
is signed, so you get negative hex representations for individual bytes, which leads to a completely bogus end result.Also,
Byte.toString
won't pad leading zeroes, which you'd want here.What is the simplest (no additional libraries, ideally no extensions) resp. most efficient fix?